#!/bin/sh

# set -e

export PATH=/root/usr/bin:/root/usr/sbin:/root/bin:/root/sbin:/usr/bin:/usr/sbin:/bin:/sbin

echo "/root/lib" >> /etc/ld.so.conf
echo "/root/usr/lib" >> /etc/ld.so.conf

mountpoint=/classmate

USERNAME=casper
USERFULLNAME="Live session user"
HOST=live
BUILD_SYSTEM=Custom

mkdir -p $mountpoint

[ -f /etc/casper.conf ] && . /etc/casper.conf
export USERNAME USERFULLNAME HOST BUILD_SYSTEM

. /scripts/casper-helpers

if [ ! -f /casper.vars ]; then
    touch /casper.vars
fi

parse_cmdline() {
    for x in $(cat /proc/cmdline); do
        case $x in
            persistent)
                export PERSISTENT="Yes" ;;
            nopersistent)
                export PERSISTENT="" ;;
            ip*)
                STATICIP=${x#ip=}
                if [ "${STATICIP}" = "" ]; then
                    STATICIP="frommedia"
                fi
                export STATICIP ;;
            ignore_uuid)
                IGNORE_UUID="Yes" ;;
	    bootfrom)
		export LIVEMEDIA=${bootfrom}
        esac
    done
}

pulsate() {
    if [ -x /sbin/usplash_write ]; then
        /sbin/usplash_write "PULSATE"
    fi
}

set_usplash_timeout() {
    if [ -x /sbin/usplash_write ]; then
        /sbin/usplash_write "TIMEOUT 120"
    fi
}

mountroot() {
    	set_usplash_timeout
    	[ "$quiet" != "y" ] && log_begin_msg "Running /scripts/casper-premount"
    	pulsate
    	run_scripts /scripts/casper-premount
    	[ "$quiet" != "y" ] && log_end_msg

    	# Needed here too because some things (*cough* udev *cough*)
    	# changes the timeout

    	set_usplash_timeout
	
	myroot="/dev/disk/by-uuid/$cmpcroot"

	# wait until the device node is there
	while [ ! -L $myroot ]; do
		sleep 1
	done
 
	mount -o rw,noatime -t ext3 $myroot $mountpoint

	modprobe loop
	modprobe squashfs

	mkdir -p /rofs
	mount -o loop -t squashfs $mountpoint/boot/classmate.squashfs /rofs || panic "Squashfs mount failed"

	modprobe unionfs

	mkdir -p /cow

	# we use the second partition on disk for rw
	rwdev="/dev/$(ls -l $myroot |sed -e 's/^.* //'|sed -e 's/[0-9./]//g')2"

	# wait until the device node is there
	while [ ! -b $rwdev ]; do 
		sleep 1
	done

	mount -o rw,noatime -t ext3  $rwdev /cow || panic "rw mount failed"

    	mount -t unionfs -o noatime,dirs=/cow=rw:/rofs=ro unionfs "$rootmnt" || panic "Unionfs mount failed"

        # make /boot available to the system
        mount -o bind ${mountpoint}/boot "${rootmnt}/boot"

    	# move the first mount; no head in busybox-initramfs
    	for d in $(mount -t squashfs | cut -d\  -f 3); do
        	mkdir -p "${rootmnt}/rofs"
        	mount -o move "${d}" "${rootmnt}/rofs"
        	break
    	done

    	log_end_msg

    	maybe_break casper-bottom

    	pulsate

        [ "$quiet" != "y" ] && log_begin_msg "Running /scripts/classmate-bottom"
    	run_scripts /scripts/classmate-bottom
    	[ "$quiet" != "y" ] && log_end_msg
}
