#!/bin/sh

echo "T2 live setup (C) 2005 - 2007 Rene Rebe, ExactCODE"

mkdir -p /tmp ; chmod 1777 /tmp

livedev=`sed -n '/[^ ]* \/media\/live/{s/ .*//p; q}' /proc/mounts`

if mount -n $livedev -o remount,rw /media/live 2>/dev/null; then
	echo "Re-mounted /media/live read-write."
fi

echo "Unionfs overlay setup ..."

dirs='/mnt/live=ro'
rw=0
for f in /media/live/live-*.*; do
	[ -e $f ] || continue

	n=${f##*/}; n=${n%.*}
	mkdir -p /mnt/$n
	if mount -nt auto -o loop,noatime $f /mnt/$n; then
		if grep -q "/mnt/$n .* rw" /proc/mounts; then
			echo "Mounted $f read-write."
			dirs="/mnt/$n=rw:$dirs"
			rw=1
		else
			echo "Mounted $f read-only."
			dirs="/mnt/$n=ro:$dirs"
		fi
	else
		echo "Failed to mount $f!"
	fi
done

# determine union fs to use, TODO: allow user-overwrite
unionfs=
modprobe aufs 2> /dev/null
if grep -q 'aufs$' /proc/filesystems; then unionfs=aufs
elif grep -q 'unionfs$' /proc/filesystems; then unionfs=unionfs
fi

if [ "$unionfs" ]; then
	if [ $rw = 0 ]; then
		mkdir -p /mnt/overlay
		mount -nt tmpfs none /mnt/overlay
		dirs="/mnt/overlay:$dirs"
	fi

	mount -nt $unionfs -o noatime,dirs=$dirs none /mnt/live

	echo "Finalizing setup ..."
	cat /proc/mounts > /etc/mtab

	find /tmp/lib -type f -name '*.ko' | while read f; do
		f=${f#/tmp}
		[ -e $f ] || mv -f /tmp/$f $f
	done
fi

# convert symlinks to bind mounts
for x in /mnt/live/* ; do
	x=${x#/mnt/live/}
	case $x in
		dev|proc|sys|media|mnt|tmp) continue ;;
	esac
	if [ -e /$x ]; then
#		echo "Removing /$x ..."
		/tmp/bin/rm -rf /$x
	fi
#	echo "Binding /mnt/live/$x /$x"
	/tmp/bin/mkdir -p /$x
	/tmp/bin/mount -t none -o bind /mnt/live/$x /$x
done

rm -rf /tmp/lib /tmp/bin /init{,2}

init="init= `cat /proc/cmdline`" ; init=${init##*init=} ; init=${init%% *}
# TODO: later on search other places if we want 100% backward compat.
[ "$init" ] || init=/sbin/init
if [ -f $init ]; then
	exec $init $*
fi

echo "No init found, giving up. Debug shell:"
exec sh --login
