#!/bin/sh
# Copyright Rene Rebe <rene@exactcode.de>

echo "T2 early userspace ..."

PATH=/sbin:/bin

echo "Mounting /dev, /proc and /sys ..."
mount -t tmpfs none /dev
mount -t proc  none /proc
mount -t usbfs none /proc/bus/usb
mount -t sysfs none /sys
ln -s /proc/self/fd /dev/fd

# later on we might reverse these, that is run udevstart first,
# and let udev add new ones as hotplug agents ...

echo "Running hotplug++ hardware detection ..."
/sbin/hotplug++ -synth
echo "/sbin/hotplug++" > /proc/sys/kernel/hotplug

echo "Loading additional subsystem and filesystem driver ..."
# hack to be removed
modprobe sbp2

# well some hardcoded help for now ...
modprobe ide-generic
modprobe ide-disk
modprobe ide-cd
modprobe sd_mod
modprobe sr_mod
modprobe sg

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

echo "Populating /dev (udev) ..."
/sbin/udevstart

echo "Searching for CD with Live file-system ..."
mkdir -p /media/cdrom /mnt/live
i=0
while [ $i -le 9 ]; do
  for x in /sys/block/*/device; do
    x=${x%/device}; x=${x#/sys/block/}
    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/fat32/vfat/'`
      if mount -t $fs -o ro $x /media/cdrom 2>/dev/null; then
	if [ -f /media/cdrom/live.squash ]; then
	  echo "Found the Live file-system ($x) ..."

	  if losetup /dev/loop0 /media/cdrom/live.squash &&
	     mount -t squashfs -o ro /dev/loop0 /mnt/live
	  then
	    # create symlinks to the live content
	    mv /bin /bin-static
	    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 ..."
			/bin-static/rm -rf /$x
		fi
#		echo "Linking /mnt/live/$x /$x"
		/bin-static/ln -s /mnt/live/$x /$x
	    done

#	    /bin-static/ls -l /
#	    echo "Removing /bin-static"
	    /bin-static/rm -rf /bin-static

	    exec /init2 $*
	  else
	    echo "Could not loop-mount squashfs."
	  fi
	else
	  echo "No Live file-system found."
	fi
	umount /media/cdrom
      fi
    done
  done
  : $(( i++ ))
  sleep 1
done

echo "No Live CD found, giving up. Debug shell:"
exec /bin/sh
