#!/bin/sh

unique_tmpdir () {
	local uniq
 	{	
		uniq=`ls /tmp | md5sum`
		uniq=${uniq%% *}
		mkdir "/tmp/${uniq}"
	} &> /dev/null
	echo "/tmp/${uniq}"
}

unpack_and_chroot () {
	local unpackdir=`unique_tmpdir`
	local packedrd=${1}
	[ -d "${1}" ] && packedrd="${1}/uInitrd"

	PATH="/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin:$PATH"

	mount -t tmpfs none "${unpackdir}"

	mkimage -l ${packedrd} 2>/dev/null

	if ( 	cd "${unpackdir}"; dd if="${packedrd}" bs=64 skip=1 2>/dev/null | gunzip 2>/dev/null | cpio -i --no-absolute-filenames 2>/dev/null ) ||
	( 	cd "${unpackdir}"; dd if="${packedrd}" bs=64 skip=1 2>/dev/null | gunzip 2>/dev/null | cpio -i 2>/dev/null )
	then
		[ -d "${1}" ] && umount "${1}"

		# inject the necessary files.  tar behaves nicely with file permissions
		tar -c /etc/ubit/ethaddr 2>/dev/null | tar -C ${unpackdir} -x
		tar -c /etc/resolv.conf 2>/dev/null | tar -C ${unpackdir} -x
		( cd /etc 2>/dev/null && tar -c ssh*key* 2>/dev/null | tar -C ${unpackdir}/etc -x )
		( cd /etc/ssh 2>/dev/null && tar -c ssh*key* 2>/dev/null | tar -C ${unpackdir}/etc -x )
		
		echo Entering UBIT environment
		if ( chroot "${unpackdir}" /start || busybox chroot "$unpackdir" /start ); then
			echo Exiting UBIT environment
		else
			echo Could not find chroot or busybox.  Exiting.
			fi
		umount "${unpackdir}"
		rmdir  "${unpackdir}"
		exit 0
	else
		[ -d "${1}" ] && umount "${1}"
		umount "${unpackdir}"
		rmdir  "${unpackdir}"
		exit 1
	fi
}

mount_and_chroot() {
	local mntdir=`unique_tmpdir`

	if ( mount -t ubifs ubi:fast ${mntdir} 2>/dev/null || mount -t ubifs ubi:silent ${mntdir} 2>/dev/null || mount -t ubifs ubi:ramdisk ${mntdir} 2>/dev/null );then
			if ( 	unpack_and_chroot "${mntdir}" ); then 
			rmdir ${mntdir}
			exit 0
		else
			rmdir ${mntdir}
			exit 1
		fi
	else
		exit 1
	fi
	}

if ( unpack_and_chroot "$(pwd)/uInitrd" ) || ( unpack_and_chroot "/boot/uInitrd" ) || ( mount_and_chroot ); then
	echo
else  
	echo "No installed UBIT ramdisk could be found."
	echo "'ubit_start' needs to be run from the directory containing the UBIT ramdisk"
	echo "or on a system with a UBIT ramdisk installed either at '/boot/uInitrd' or in 
	echo a UBIFS partition named 'fast', 'silent' or 'ramdisk'"
fi
