#! /bin/bash
# all offsets and numbers are for rsa2048

eswap=../../tools/sswap32
action="split"

case $1 in
    -s )
        action="split" ;;
    -i )
        action="inject" ;;
    * )
        echo "Invalid parameter"
        exit 1 ;;
esac

if [ ${action} == "split" ] ; then

# separate stage 1
dd if=bootloader12.bin bs=32K count=1 | ${eswap} > bootloader.s1.bin
# remove the hole. numbers are for rsa2048 keys.
dd if=bootloader.s1.bin of=bootloader.s11.bin bs=64 count=16
dd if=bootloader.s1.bin of=bootloader.s12.bin bs=64 skip=33
# combine both images to form stage 1
cat bootloader.s11.bin bootloader.s12.bin > bootloader.s1.bin
rm -f bootloader.s11.bin bootloader.s12.bin
#extract stage 2
stage2_address=`awk '/_stage2_start/ { print $1 ; }' bootloader12.map`
stage2_off=$((($stage2_address & 0xffff)/0x40))
dd if=bootloader12.bin bs=64 skip=${stage2_off} | ${eswap} > bootloader.s2.bin

else

# reverse endianness 
cat bootloader.s1.sig | ${eswap} > bootloader.s1s.sig
cat bootloader.s2.sig | ${eswap} > bootloader.s2s.sig
# inject signatures
dd if=bootloader.s1s.sig of=bootloader12.bin bs=64 seek=29 conv=notrunc
cat bootloader12.bin bootloader.s2s.sig > bootloader12.sbin

fi