1#!/bin/sh
2# $NetBSD: walnut-mkimg.sh,v 1.4 2010/11/06 16:23:35 uebayasi Exp $
3
4# Convert an input to a TFTP image loadable by the IBM PowerPC OpenBIOS.
5
6magic=5394511	# IBM OpenBIOS magic number 0x0052504f
7start=0
8size=0
9overwrite=0
10
11if [ $# -ne 2 ] ; then
12	echo usage: $0 input image 1>&2
13	exit 1
14fi
15
16input=$1; shift
17output=$1; shift
18
19: ${OBJDUMP=objdump}
20: ${OBJCOPY=objcopy}
21: ${STAT=stat}
22
23file=$( file $input )
24case $file in
25*:\ ELF\ *)
26	start=`${OBJDUMP} -f ${input} | awk '/start address/ { print $NF }'`
27	start=`printf "%d" $start`
28	${OBJCOPY} -O binary ${input} ${input}.bin.$$
29	;;
30*)
31	case $file in
32	*\ [Ff]ile\ [Ss]ystem*|*\ [Ff]ilesystem*)
33		overwrite=1
34		;;
35	esac
36	cp ${input} ${input}.bin.$$
37	;;
38esac
39
40size=$(${STAT} -f '%z' ${input}.bin.$$)
41size=$(( ( $size + 511 ) / 512 ))
42
43enc()
44{
45	local _x=$1; shift
46	printf $( printf '\\x%x' $_x )
47}
48
49be32enc()
50{
51	local _x=$1; shift
52	enc $(( ( $_x >> 24 ) & 0xff ))
53	enc $(( ( $_x >> 16 ) & 0xff ))
54	enc $(( ( $_x >>  8 ) & 0xff ))
55	enc $(( ( $_x >>  0 ) & 0xff ))
56}
57
58{
59	be32enc $magic
60	be32enc $start
61	be32enc $size
62	be32enc 0
63	be32enc $start
64	be32enc 0
65	be32enc 0
66	be32enc 0
67} > ${input}.hdr.$$
68
69if [ $overwrite = 0 ]; then
70	cat ${input}.hdr.$$ ${input}.bin.$$ > ${output}
71else
72	cp ${input}.bin.$$ ${output}
73	dd if=${input}.hdr.$$ of=${output} conv=notrunc
74fi
75
76rm -f ${input}.hdr.$$ ${input}.bin.$$
77exit
78