#!/bin/bash

ID="livecd"

TMP_MOUNT="/mount"

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

if [ ! -d /proc ];then
mkdir /proc
fi

mount -n proc /proc -t proc

if ! grep -q '[[:space:]]sysfs' /proc/mounts;then
	if [ ! -d /sys/block ];then
	mount -t sysfs -n sysfs /sys
	fi
fi

mount -n ramfs /dev -t ramfs

# make some dirs
mkdir -v /dev/pts
mkdir -v /dev/shm

/sbin/udevd --daemon

/sbin/udevadm settle

# detect the livecd

echo "Detecting cdrom devices..."
for I in `find /proc/sys/dev/cdrom | xargs grep -s "drive name" | awk '{ print $3 }'`
do CDROM_LIST="$CDROM_LIST /dev/$I"
done

# now we try to find the livecd using it's ID

LIVE_DEVICE=""

for cdrom_device in $CDROM_LIST
do
mount -n -t iso9660 ${cdrom_device} $TMP_MOUNT
media_found=$?

	if [ $media_found -eq 0 ];then
	echo -n "Media found"
	[ -e "$TMP_MOUNT/$ID" ]
	media_live=$?

	if [ $media_live -eq 0 ];then
	echo -n ". Livecd found."
	LIVE_DEVICE="$cdrom_device"
	break;
	else
	echo ". Not livecd."
	umount -n $TMP_MOUNT
	fi
else
	echo "No media found"
fi
done

if [ $LIVE_DEVICE = "" ];then
	echo "LiveCD not found! Halting system."
	exit 1
else
	echo " Booting from $LIVE_DEVICE..."

	echo 0x0100 > /proc/sys/kernel/real-root-dev
	cd $TMP_MOUNT
	pivot_root . mount
	exec chroot . sh -c 'umount -l -n /mount;
	exec -a init.new /sbin/init 3' <dev/console >dev/console 2>&1
fi
