#!/bin/sh

currentdir=`pwd`

ANDROID_OUT=out
ANDROID_DEVICE=freerunner
EXPORT_ROOT=$currentdir/build_jffs2_tmp

Usage()
{
	echo "Usage: $0 release|debug jffs2filename"
}

BuildImage()
{

	if [ -d $1 ]
	then
		echo "[INFO] Copying from... $1"

		sudo rm -rf $EXPORT_ROOT
		mkdir $EXPORT_ROOT
		mkdir $EXPORT_ROOT/root

		# Copy the image...
		cd $1
		tar cf - root | (cd $EXPORT_ROOT; sudo tar xf -)
		tar cf - system | (cd $EXPORT_ROOT/root; sudo tar xf -)

		# Change owner and permissions...
		cd $EXPORT_ROOT
		sudo chown -R root:root root
		sudo chmod -R 777 root
		
		cd $currentdir

		# Make the JFFS2 file
		mkfs.jffs2 --pad=0x700000 -o $2 -e 0x20000 -n -d$EXPORT_ROOT/root/
		echo "[INFO] Image written to $2"
		
		sudo rm -rf $EXPORT_ROOT
	else
		echo "$1 does not exist!"
	fi
}

if [ $# != 2 ]
then
	Usage
else

	case $1 in
	    release)
		BuildImage $ANDROID_OUT/target/product/$ANDROID_DEVICE $2
		;;
	    debug)
		BuildImage $ANDROID_OUT/debug/target/product/$ANDROID_DEVICE $2
		;;
	    *)
		Usage
	esac
fi
