#!/bin/sh
#creates a file containing a ext3 binary blob of the content of the ./rootfs folder

Usage()
{
	echo "creates a file containing a ext3 binary blob. Output file name taken from command line"
	echo "Usage: genext3fs.sh [OPTION]... dest_file_name"
	echo "-h : Prints this message"
	echo "-b : Sets the partition size in MBytes, default 256"
	echo "-d : Selects the directory which contains the partition content, default ../rootfs"
	echo ""
}

PARTITIONSIZE=256
SRCPATH=../rootfs

while getopts "b:d:h" Option ; do
	case $Option in
		h) Usage
			# Exit if only usage (-h) was specfied.
			if [[ $# -eq 1 ]] ; then
				exit 10
			fi
			exit 0
			;;
		b) PARTITIONSIZE=$OPTARG
			;;
		d) SRCPATH=$OPTARG
			;;
	esac
done
#adjust the commandline arg for the now used options
shift $(($OPTIND - 1))

#create the file used for the loopbackdevice and format it for ext3
#answer y to "is not a block special device"
dd if=/dev/zero of=$@ bs=1024k count=$PARTITIONSIZE
mkfs.ext3 -F -L arm $@

#prepare mountpoint for the loopdevice 
sudo mkdir -p mnt/rootfs
sudo umount mnt/rootfs &> /dev/null
sudo rm -rf mnt/rootfs/*
#mount the file as a loopdevice 
#there seems to be a race between mkfs.ext3 not yet finished and mount already trying to mount, so try until it works
MOUNTED=0
while [ "$MOUNTED" -eq  "0" ] ; do
	sync
	sleep 1
	sudo mount $@ mnt/rootfs/ -o loop -t ext3
	MOUNTED=`mount | grep -c "$@"`
done
#extract rootfs into the file
sudo cp -rpP $SRCPATH/* mnt/rootfs

#unmount again
sudo umount mnt/rootfs

#if the mounting was unsuccesful all rootfs data now still is in mnt/rootfs, and $@ is an empty fs
#delete $@ in that case to fail early
FAILED=`ls mnt/rootfs/ | wc -l`
if [ "$FAILED" -ne "0" ] ; then
	echo "mounting the loopdevice $@ failed"
	sudo rm $@
fi
