#!/bin/sh
#
# mkramdisk - by jmalone@applieddata.net
#
# Copyright 2004-2006 Joshua Malone, Applied Data Systems
#
# This file is subject to the terms and conditions of the GNU General Public
# License.
#

mntpoint=/mnt/loop

VARDIR=/var/lib/adsrootbuilder
LIBDIR=/usr/share/adsrootbuilder

# Common fstab lines
FSTAB="none      /dev/pts  devpts  mode=0622   0  0
proc      /proc     proc    defaults    0  0
/dev/hda1 /mnt/hda  vfat    rw,noauto
/dev/sda1 /mnt/sda  vfat    rw,noauto
/dev/mmc1 /mnt/mmc  vfat    rw,noauto"

# Include "library" of shell functions
. $LIBDIR/adsshell.inc
	
# Avoid using busybox tar.
if [ -x "$(which tar.orig)" ]; then
	TAR="$(which tar.orig)"
else
	TAR=tar
fi

# Function defs

printusage () {
	echo "Usage:"
	echo " mkrootimg -t <fstype> [-p <path>] [-x <path>[,<path>]] [-r][-R] <tarfile> <image>"
	echo ""
	echo "Where:"
	echo "   fstype := ext2 || e2fs     - Traditional ext2 ramdisk image"
	echo "             cramfs           - Compressed ROM filesystem image"
	echo "             jffs2            - Journalling flash filesystem image"
	echo ""
	echo "   -p        - Use <path> in the tarball as the root for the filesystem"
	echo "   -x        - Exclude <path> from the filesystem"
	echo "   -r        - Convert /tmp to ramfs filesystem (only for /)"
	echo "   -R        - Convert /var to ramfs filesystem (only for / on JFFS2)"
	echo "   tarfile   - Tarball generated from running system"
	echo "   image     - File to write image to"
	echo ""
}

tweakfs () {
	if [ -z "$1" ]; then
		errexit "Oops - improper call to tweakfs()"
	else
		mntpoint=$1
	fi
	
	# Tweak the rootfs a bit
	echo "Making rootfs tweaks..."
	workdir=$(pwd)
	echo "  Creating /proc mount point"
	mkdir ${mntpoint}/proc
	echo "  Clearing /var/run"
	for i in ${mntpoint}/var/run/*.pid; do
		rm -f $i 2>&1 >/dev/null
	done
	if [ -f ${mntpoint}/var/run/utmp ]; then
		rm ${mntpoint}/var/run/utmp
	fi
	echo "  Clearing /tmp"
	if [ -d ${mntpoint}/tmp ]; then
		rm -rf ${mntpoint}/tmp
	fi
	mkdir ${mntpoint}/tmp
	chmod 1777 ${mntpoint}/tmp
}

var_to_ramfs () {

	if [ -z "$1" ]; then
		errexit "Oops - improper call to var_to_ramfs()"
	fi
	if ! [ -d ${1}/var ]; then
		errexit "No /var found in this image and you requested ramfs var!"
	else
		pushd ${1}/var
	fi

	$TAR cf ../.var.tar .
	cd ..
	rm -rf var
	mkdir var

	echo "Converted /var to $(du -sk .var.tar | cut -f 1)k tarball"

	if ! [ -d etc/init.d ]; then
		echo "WARNING:"
		echo "Your image does not appear to contain /etc/init.d!"
		errexit "Cannot install var mount/unmount scripts!"
	fi

	cat > etc/init.d/mountvar.sh <<EOF
#!/bin/sh
# Adapted from familiar gpe-0.7.1 Linuxrc
#
echo "Setting up RAMFS, please wait..."
#mount -n /proc
mount /var
tar -C /var -xf /.var.tar > /dev/null 2>&1
EOF
	chmod a+x etc/init.d/mountvar.sh
	if ! [ -d etc/rcS.d ]; then
	    echo "Warning: no init scripts for runlevel S"
	else
	    ln -s ../init.d/mountvar.sh etc/rcS.d/S10mountvar.sh
	fi

	
	
	cat > etc/init.d/savevar.sh <<EOF
#!/bin/sh
echo "Saving contents of /var..."
tar -C /var -cf /tmp/var.tar . >/dev/null 2>&1
mv -f /tmp/var.tar /.var.tar
EOF
	chmod a+x etc/init.d/savevar.sh
	if ! [ -d etc/rc0.d ]; then
	    echo "Warning: no init scripts for runlevel 0"
	else
	    ln -s ../init.d/savevar.sh etc/rc0.d/S37savevar.sh
	fi
	if ! [ -d etc/rc6.d ]; then
	    echo "Warning: no init scripts for runlevel 6"
	else
	    ln -s ../init.d/savevar.sh etc/rc6.d/S37savevar.sh
	fi

	# Return to previous dir
	popd

}


untar_root() {
	# Use: untar_root <tarfile> <temp working dir> [<path to extract>] [<exclude>]
	if [ -z "$2" ]; then
		errexit "internal error in unter_root()"
	fi
	tarfile=$1
	tmpdir=$2
	if ! [ -z "$3" ]; then
		tarpath="$3"
	else
		tarpath="/"
	fi
	if ! [ -z "$4" ]; then
		exclude="$4"
	fi

	startdir=$(pwd)
	# untar the tarball for use by another tool
	if [ "${checktmpdir}" != 'n' ]; then
		if [ -d ${tmpdir} ]; then
			read -p "Overwrite temporary directory ${tmpdir} (y/n)? " yorn
			if ! yesorno $yorn; then
				echo "Aborting"
				exit
			else
				rm -r ${tmpdir}
			fi
			if [ -d ${tmpdir} ]; then
				errexit "Cannot overwrite temp directory ${tmpdir}"
			fi
		fi
		mkdir ${tmpdir}
		if ! [ -d ${tmpdir} ]; then
			errexit "Can't create temporary work directory ${tmpdir}"
		fi
	fi

	# Replace a path of '/' with null since GNU tar doesn't interpret
	#  / correctly
	if [ "${tarpath}" == '/' ]; then
		tarpath=""
	fi

	# Set up exclude paths (if any)
	if ! [ -z "${exclude}" ]; then
		taropts=""
		IFS=,
		for i in ${exclude}; do
			taropts="${taropts} --exclude ${i}"
		done
		IFS=" "
	fi

#	# For pax
#	# Set up exclude paths
#	if ! [ -z "${exclude}" ]; then
#		taropts=""
#		IFS=,
#		for i in ${exclude}; do
#			taropts="${taropts} -c ${i}"
#		done
#		IFS=" "
#	fi

	# Append the path to extract to the options string
	taropts="${taropts} ${tarpath}"

	echo -n "Extracting root tarball...   "
	$TAR -C ${tmpdir} -xpf ${tarfile} ${taropts} 2>&1 |grep -v "Removing leading"

	# Use pax instead for extraction
	#if [ "$(dirname ${tarfile})" == "." ]; then
	#	tarfile=$(pwd)/${tarfile}
	#fi
	#cd ${tmpdir}
	#pax -r -pe -k -s,^/,, -f ${tarfile} ${taropts}      
	#cd ${startdir}

	sync

	# Create mount points for paths that we excluded
	IFS=,
	for i in "${exclude}"; do
		if ! [ -z "${i}" ]; then
			mkdir ${tmpdir}${i}
		fi
	done
	IFS=" "

	echo "done"
}

mktweakedtarball () {
	tarfile="$1"
	dir="$2"

	if [ -e ${tarfile} ]; then
		read -p "File named ${tarfile} exists - overwrite (y/n)? " yorn
		if yesorno $yorn; then
			rm ${tarfile}
			if ! [ $? ]; then
				errexit "Cannot delete old tarfile"
			fi
		else
			echo "Aborting!"
			exit
		fi
	fi

	echo -n "Creating tweaked tarball $tarfile ...   "
	(
	cd $dir
	$TAR -cf ${tarfile} . 2>/dev/null
	)
	echo "done"
}

#############

exclude=""

if [ -z "$1" ] || [ "$1" == '-h' ]; then
	printusage
	exit
fi

if [ "$1" == '-t' ]; then
	if [ -z "$2" ]; then
		errexit "Must specify filesystem type"
	else
		fstype="$2"
	fi
	shift
	shift
fi
tarpath="/"
if [ "$1" == '-p' ]; then
	# Use only a specific path from the tarball
	if [ -z "$2" ]; then
		errexit "Must specify path when using -p"
	else
		tarpath=$2
		shift
	fi
	shift
fi
# Check for exclude path
if [ "$1" == '-x' ]; then
	if ! [ -z "$2" ]; then
		# For convinience, exclude path can be null
		exclude="$2"
		shift
	fi
	shift
fi
# Check for ramfs_tmp signal
if [ "$1" == '-r' ]; then
	ramfs_tmp='y'
	shift
fi
#Check for ramfs_var signal
if [ "$1" == '-R' ]; then
	ramfs_var='y'
	shift
fi

# Grab required parameters
if [ -z "$1" ]; then
	errexit "Must specify tarfile name"
else
	tarfile=$1
	shift
fi

if [ -z "$1" ]; then
	errexit "Must specify filename for ramdisk image"
else
	rdimage=$1
fi

if ! [ -f ${tarfile} ]; then
	errexit "Tar file ${tarfile} not found"
fi

if [ -e ${rdimage} ]; then
	read -p "Old image file ${rdimage} exists - Overwrite (y/n)? " yorn
	if yesorno $yorn; then
		rm ${rdimage}
		if ! [ $? ]; then
			errexit "Unable to delete ${rdimage}"
		fi
	else
		echo "Aborting!"
		exit
	fi
fi

# Determine size of tarfile
tarsize=$(du -k ${tarfile} | sed -e "s/[ 	].*//")
if [ ${tarsize} -gt 32000 ]; then
	# Suggest that the image is too big
	echo ""
	echo "WARNING:  Your tar file size is over 32MB!"
	echo "You may wish to tune your system prior to building the"
	echo "ramdisk to reduce the root filesystem size."
	echo
	read -p "Continue anyway (y/n)? " yorn
	if [ -n "$yorn" ] && ! yesorno $yorn; then
		echo "Aborting at user request"
		exit
	fi
fi
if [ ${tarsize} -gt 62000 ]; then
	# We only have 64MB of flash on the board - so we must fail
	errexit "Tar file size exceeds available flash (64MB)"
fi

tmpdir="$VARDIR/.adstemp"

# Generate the FS image
case ${fstype} in

ext2|e2fs)

	# Use the perl tool to get a real size
	#tarsize=$( tarsize ${tarfile} ${tarpath} )
	# NOTE: this produces a number that's too low  :(

	# Crappy fudge factor to make sure ramdisk is big enough
	# in kilobytes
	tarsize=$(( ${tarsize} + 1000 ))
	echo "Debug: tarsize is ${tarsize}"

	# Compensate for the size of excluded filesystems by
	# reducing tarsize appropriately (to avoid wasting ram on a
	# ramdisk sized for more files than are actually there)
	if ! [ -z "${exclude}" ]; then
		echo -n "Calculating space reclaimed by excluded filesystems...   "
		for i in "${exclude}"; do
			reduce=$(tarsize ${tarfile} $i)
			tarsize=$(( ${tarsize} - ${reduce} ))
		done
		echo "done"
		echo "Excluded filesystems reduce size to ${tarsize}"
	fi
	
	# Generate an empty ext2 filesystem image for use as ramdisk
	echo -n "Generating ramdisk image file...   "
	dd if=/dev/zero of=${rdimage} bs=1k count=${tarsize} &> /dev/null
	if ! [ -f ${rdimage} ]; then
		errexit "Unable to create image file"
	else
		echo "done"
	fi
	echo ''
	echo "Formatting ramdisk as ${fstype}...   "
	echo ""
	mke2fs -F -m 1 -q ${rdimage}
	if ! tune2fs -i 0 -c 0 ${rdimage}; then
		errexit "Problem creating ext2 filesystem in ${rdimage}"
	fi
	echo "done"

	# Mount the filesystem
	echo -n "Mounting ramdisk image...   "
	if ! [ -d ${mntpoint} ]; then
		echo "Creating loopback image mounting point at ${mntpoint}"
		mkdir ${mntpoint}
		if ! [ -d ${mntpoint} ]; then
			errexit "Loopback mount point ${mntpoint} not avaiable"
		fi
	fi
	mount -o loop ${rdimage} ${mntpoint}
	if ! [ $? ]; then
		errexit "Unable to mount ${rdimage} at ${mntpoint}"
	fi
	echo "done"

	# Extract the root filesystem contents into the ramdisk image
	checktmpdir='n'
	untar_root "${tarfile}" "${mntpoint}" "${tarpath}" "${exclude}"

	# Tweaks that apply only if this is the root filesystem
	if [ "${tarpath}" == '' ] || [ "${tarpath}" == '/' ]; then
		tweakfs ${mntpoint}

		echo -n "  Creating /etc/fstab...   "
		echo "/dev/ram  /       ext2    defaults    0  0" > ${mntpoint}/etc/fstab
		echo ${FSTAB} >> ${mntpoint}/etc/fstab
		if [ "${ramfs_tmp}" == 'y' ]; then
		echo "ramfs     /tmp    ramfs   size=4m     0  0" >>${mntpoint}/etc/fstab
		fi
		echo "done"

		echo "Done tweaking"
	fi

	# Report usage
	echo " ## Ramdisk usage:        Total KB  Used KB    Free KB"
	df -k ${mntpoint}
	echo

	mktweakedtarball ${rdimage}.tar ${mntpoint}

	# Unmount the filesystem
	sleep 5
	if ! umount ${mntpoint}; then
		errexit "Unable to unmount ramdisk filesystem from ${mntpoint}"
	fi

	echo "Created uncompressed EXT2 filesystem image: ${rdimage}"
	;;

cramfs)
	# Compressed read-only filesystem
	if ! [ -x $(which mkcramfs) ]; then
		errexit "mkcramfs not found - try apt-get install mkcramfs"
	fi

	# Extract tarball (or relevant portion)
	untar_root ${tarfile} ${tmpdir} ${tarpath} ${exclude}

	# Tweaks that apply only if this is the root filesystem
	if [ "${tarpath}" == '/' ] || [ "${tarpath}" == '' ]; then
		tweakfs ${tmpdir}

		# Update fstab
		echo -n "  Creating /etc/fstab...   "
		echo "/dev/root  /       cramfs   defaults    0  0" > ${tmpdir}/etc/fstab
		echo ${FSTAB} >> ${tmpdir}/etc/fstab
		if [ "${ramfs_tmp}" == 'y' ]; then
			echo "ramfs      /tmp    ramfs    size=4m     0  0" >>${tmpdir}/etc/fstab
		fi
	        if [ "${ramfs_var}" == 'y' ]; then
	        	echo "ramfs     /var    ramfs   size=4m,noauto 0     0" >> ${tmpdir}/etc/fstab
			var_to_ramfs ${tmpdir}
		fi
		echo "done"

		echo "Done tweaking"
	fi
	
	mktweakedtarball ${rdimage}.tar ${tmpdir}
	
	echo -n "Generating cramfs filesystem...   "
	mkcramfs ${tmpdir} ${rdimage}  >/dev/null
	echo "done"

	echo -n "Cleaning up temporary directory...   "
	rm -rf ${tmpdir}
	echo "done"
	echo
	echo "Done creating cramfs image: ${rdimage}"
	;;

jffs2)
	# Journalling flash filesystem 2
	if ! [ -x $(which mkfs.jffs2) ]; then
		errexit "mkfs.jffs2 not found - try apt-get install mtd-tools"
	fi
	
	untar_root ${tarfile} ${tmpdir} ${tarpath} ${exclude}

	# Tweaks that apply only if this is the root filesystem
	if [ "${tarpath}" == '/' ] || [ "${tarpath}" == '' ]; then
	    tweakfs ${tmpdir}

	    echo -n "Creating /etc/fstab...   "
	    echo "/dev/root   /       jffs2   defaults  0   0" >  ${tmpdir}/etc/fstab
	    echo ${FSTAB} >> ${tmpdir}/etc/fstab
	    if [ "${ramfs_tmp}" == 'y' ]; then
	    echo "ramfs       /tmp    ramfs   size=4m   0   0" >> ${tmpdir}/etc/fstab
	    fi
	    if [ "${ramfs_var}" == 'y' ]; then
	      echo "ramfs     /var    ramfs   size=4m,noauto 0     0" >> ${tmpdir}/etc/fstab
	      var_to_ramfs ${tmpdir}
	    fi
	    echo "done"

	    echo "Done tweaking"
	fi	

	# This hack added because of a strange interaction between
	# /etc/init.d/checkroot.sh and jffs; if run from jffs, the script
	# always sets rootcheck=yes, even if pass is 0. If run from a
	# different filesystem, it does not have this behavior. 
	# Workaround: disable script.
	cat > ${tmpdir}/etc/init.d/checkroot.sh <<EOF
#!/bin/sh
mount -o remount,rw /
EOF
	
	mktweakedtarball ${rdimage}.tar ${tmpdir}
	
	echo "Creating JFFS2 filesystem images..."
	mkfs.jffs2 -e 0x40000 -p -r ${tmpdir} -o ${rdimage}
	mkfs.jffs2 -e 0x20000 -p -r ${tmpdir} -o ${rdimage}-128k
	echo "done"

	echo -n "Cleaning up temporary directory...   "
	rm -rf ${tmpdir}
	echo "done"
	echo
	echo "Done creating JFFS2 image: ${rdimage}"
	;;

*)
	errexit "Filesystem type ${fstype} is unknown"
	;;
esac

