#!/bin/sh

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

mkdir -p /tmp ; chmod 1777 /tmp

livedev=`sed -n '/[^ ]* \/media\/live/{s/ .*//p; q}' /proc/mounts`
if mount -n $livedev /media/live -o remount,rw; then
	echo "Re-mounted /media/live writeable."
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

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

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

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
rm -rf /tmp/lib /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
