#!/bin/sh

echo "T2 SDE early (live) userspace (C) 2005 - 2008 Rene Rebe, ExactCODE"

PATH=/sbin:/bin:/usr/bin:/usr/sbin

echo "Mounting /dev, /proc and /sys ..."
mount -t tmpfs none /dev -o mode=755
mount -t proc  none /proc
mount -t usbfs none /proc/bus/usb 2> /dev/null
mount -t sysfs none /sys
ln -s /proc/self/fd /dev/fd

echo "Populating u/dev ..."
mknod /dev/null c 1 3
mknod /dev/zero c 1 5
udevd &
udevtrigger
udevsettle
[ -e /dev/console ] || mknod /dev/console c 5 1
[ -e /dev/tty ] || mknod /dev/tty c 5 0

echo "Loading additional subsystem and filesystem driver ..."

# well some hardcoded help for now ...
for x in sbp2 ide-generic ide-disk ide-cd sd_mod sr_mod sg; do
	modprobe $x 2> /dev/null
done

# the modular filesystems ...
for x in /lib/modules/*/kernel/fs/{*/,}*.*o ; do
	x=${x##*/} ; x=${x%.*o}
	modprobe $x 2> /dev/null
done

live="live=live.squash `cat /proc/cmdline`" ; live=${live##*live=} ; live=${live%% *}
echo "Searching for media with $live image ..."
mkdir -p /{media,mnt}/live
i=0
while [ $i -le 14 ]; do
  for x in /sys/block/*/device; do
    x=${x%/device}; x=${x#/sys/block/}
    [ "$x" = "*" ] && continue
    # TODO: make option to skip fixed devices
    #case "`ls -l /sys/block/$x/device`" in 
    #  */usb*|*/ieee1394) : ;;
    #  *) [ "`cat /sys/block/$x/removable`" = 1 ] || continue ;;
    #esac
    x=/dev/$x
    for x in ${x}* ; do
      [ -e $x ] || continue
      fs=`disktype $x 2>/dev/null |
          sed -e '/file system/!d' -e 's/file system.*//' -e 's/ //g' \
              -e 'y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/' \
              -e 's/fat.*/vfat/' | sed -n '$p'`
      [ $i -gt 2 ] && echo "Testing device $x, type $fs ..."
      if mount -t $fs -o ro $x /media/live 2>/dev/null; then
	[ $i -gt 0 ] && echo "Successfully mounted $x ..."
	if [ -f /media/live/$live ]; then
	  echo "Found the $live image on $x."

	  if losetup /dev/loop0 /media/live/$live &&
	     mount -t squashfs -o ro /dev/loop0 /mnt/live
	  then
	    kill %1

	    # setup final directory structure
	    mkdir -p /tmp/bin
	    mv /lib /tmp/
	    mv /bin/* /sbin/* /tmp/bin/
	    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 "Sym-linking /mnt/live/$x /$x"
		/tmp/bin/ln -s /mnt/live/$x /$x
	    done

#	    /tmp/bin/ls -l / /tmp
#	    /tmp/bin/rm -rf /tmp/bin

	    exec /init2 $*
	  else
	    echo "Failed to loop-mount $live."
	    losetup -d /dev/loop0
	  fi
	else
	  echo "No $live image found."
	fi
	umount /media/live
      fi
    done
  done
  : $(( i++ ))
  sleep 1
done

echo "No live media found, giving up. Debug shell:"
exec /bin/sh
