#!/bin/sh

UPDATE_TOOL="python `pwd`/kindle_update_tool_lite.py"
KEY="`pwd`/sign.key"
FOLDERS=`ls`
TEMP=`pwd`/.tmp-$$
OUTPUT=`pwd`/output

clean()
{
	find . -type f -name '.DS_Store' -or -type f -name '._*' -exec rm -f {} \;
	rm -r ${OUTPUT}
	mkdir ${TEMP}
	mkdir ${OUTPUT}
}

package_kernel()
{
	DIR=$1
	OUTDIR=$2
	
	md5sum ${DIR}/uImage | awk '{printf $1}' > ${OUTDIR}/kernel.md5
	tar -C ${DIR} -czf ${OUTDIR}/kernel.tar.gz uImage uImage.partitions
	rm -rf ${DIR}
}

sign_everything()
{
	FOLDER=$1
	NAME=$2
	DAT=${FOLDER}/update-${NAME}.dat
	find ${FOLDER} -type f | sort > ${TMP}/file-list
	while read line
	do
		FILENAME=$line
		openssl dgst -sha256 -sign ${KEY} -out ${FILENAME}.sig ${FILENAME}
		TYPE=128
		if [ "`echo ${FILENAME} | awk -F . '{print $NF}'`" == "ffs" ]; then
			TYPE=129
		fi
		MD5=`md5sum ${FILENAME} | awk '{print $1}'`
		FILESIZE=`ls -nl ${FILENAME} | awk '{print $5}'`
		SIZE=`expr ${FILESIZE} / 64`
		LOC=${FILENAME/${FOLDER}\/}
		echo "${TYPE} ${MD5} ${LOC} ${SIZE} ${LOC}" >> ${DAT}
	done < ${TMP}/file-list
	openssl dgst -sha256 -sign ${KEY} -out ${DAT}.sig ${DAT}
}

clean

for item in ${FOLDERS}; do
	if [ ! -d $item ]; then
		continue;
	fi
	NAME=`echo ${item} | awk -F - '{print $1}'`
	DEVICE=`echo ${item} | awk -F - '{print $2}'`
	MINVERSION=`echo ${item} | awk -F - '{print $3}'`
	MAXVERSION=`echo ${item} | awk -F - '{print $4}'`
	
	STORE=${TEMP}/${item}
	[ -d ${STORE} ] || mkdir ${STORE}
	cp -a $item/* ${STORE}
	
	if [ -d ${STORE}/kernel ]; then
		package_kernel ${STORE}/kernel ${STORE}
	fi
	
	sign_everything ${STORE} ${NAME}
	tar -C "${STORE}" -czf "${TEMP}/${NAME}.tar.gz" .
	
	${UPDATE_TOOL} c ${MINVERSION} `expr ${MAXVERSION} + 1` ${DEVICE} FC02 "${TEMP}/${NAME}.tar.gz" ${OUTPUT}/update_${NAME}.bin
done

rm -rf ${TEMP}