#!/bin/sh

MBR=../../mbr/sd_default
INITRD=../../initrd/sd_default
KERNEL=../../kernel/sd_default
FS=../../debian/sd_default

MBR_SIZE=16384
INITRD_SIZE=1048576
KERNEL_SIZE=1556480
EXTRA_SPACE=2359296 #extra space set aside prior to the fileystem
FS_SIZE=244842496

echo "Creating SD card image"

#don't recreate an empty file of 256MB if it already exists
if test ! -f debian.dd; then
	echo -ne "\tCreating 256MB empty file," 
	echo "this will take several minutes" 
	dd if=/dev/zero of=debian.dd bs=$FS_SIZE count=1 \
	  conv=sync >/dev/null 
	if test "$?" != "0"; then exit; fi
fi

#EWD: We could make this more efficient by only  updating debian.dd if 
# debian.dd is older than #$FS
echo -ne "\tConverting .tar filesystem to dd compatible file"
echo -n "." && \
mkfs.ext2 -Fq debian.dd >/dev/null && \
echo -n "." && \
tune2fs -i 0 debian.dd >/dev/null && \
echo -n "." && \
#umount mnt >/dev/null 2>&1 && \
mount -o loop debian.dd mnt >/dev/null && \
echo -n "." && \
tar xf $FS -C mnt >/dev/null && \
echo -n "." && \
umount mnt >/dev/null && \
echo "." && \

#Create the final dd image
echo -e "\tWriting MBR" && \
dd if=$MBR bs=$MBR_SIZE count=1 of=sdimage.dd && \
echo -e "\tWriting Kernel" && \
dd if=$KERNEL bs=$KERNEL_SIZE count=1 obs=1 seek=$MBR_SIZE \
  of=sdimage.dd && \
echo -e "\tWriting Initial Ramdisk" && \
dd if=$INITRD bs=$INITRD_SIZE count=1 obs=1  \
  seek=`expr $MBR_SIZE + $KERNEL_SIZE` of=sdimage.dd && \
echo -e "\tWriting Filesystem" && \
dd if=debian.dd bs=$FS_SIZE count=1 obs=1 \
  seek=`expr $MBR_SIZE + $KERNEL_SIZE + $INITRD_SIZE + $EXTRA_SPACE` \
  of=sdimage.dd && \

#Create precomputed CRCs
echo -e "\tPrecomputing CRCs" && \
./dd2sdrawimg < sdimage.dd > ../sdrawimg_current
#rm -f sdimage.dd
echo  "Done"

echo "Don't forget to update /u/home/ftp/ts-arm-linux-cd/binaries/ts-images/sdimage.dd"
echo "or delete bin/sdimage.dd"
