#!/bin/sh

if [ $# -ne 6 ]; then
	echo "Usage: $0 -t type -d deviceCode input.tar.gz output.bin"
	exit 1
fi

DEVICE=$4
TYPE=$2
INPUT=$5
OUTPUT=$6

HEADER_SIZE=48
BLOCK_SIZE=64
if [ "${TYPE}" == "FB02" -o "${TYPE}" == "FB01" ]; then
	BLOCK_SIZE=131072
fi

MD=`pwd`/md

echo 'Checking parameters...'
if [ ${#DEVICE} -ne 2 ]; then
	echo 'deviceCode must be a two digit number. ex: 02'
	exit 1
fi
TYPE=`echo "${TYPE}" | tr "[a-z]" "[A-Z]"`
if [ ${#TYPE} -ne 4 ]; then
	echo 'type must be 4 characters long. ex: FC02'
	exit 1
fi
if [ ! -f ${INPUT} ]; then
	echo 'cannot find input'
	exit 1
fi

echo 'Making header...'

echo -e "${TYPE}\x00\x00\x00\x00\xFF\xFF\xFF\x7F\x${DEVICE}\x00\x00" > ${OUTPUT}

echo 'Calculating MD5 hash...'
md5sum ${INPUT} | awk '{printf $1}' | ${MD} >> ${OUTPUT}

echo 'Adding header padding...'
COUNT=`expr ${BLOCK_SIZE} - ${HEADER_SIZE}`
dd if=/dev/zero of=${OUTPUT}-zeros.bin bs=${COUNT} count=1
cat ${OUTPUT}-zeros.bin >> ${OUTPUT}
rm -f ${OUTPUT}-zeros.bin

echo 'Adding tar...'
cat ${INPUT} | ${MD} >> ${OUTPUT}

echo 'Done.'

exit 0