#!/bin/sh

PREREQ=""

prereqs()
{
       echo "$PREREQ"
}

case $1 in
# get pre-requisites
prereqs)
       prereqs
       exit 0
       ;;
esac


. /scripts/casper-functions
. /scripts/casper-helpers

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

casper_parse_cmdline() {
    for x in $(cat /proc/cmdline); do
        case $x in
            showmounts|show-cow)
                export SHOWMOUNTS='Yes' ;;
            persistent)
                export PERSISTENT="Yes" ;;
            nopersistent)
                export PERSISTENT="" ;;
            persistent-path=*)
                export PERSISTENT_PATH="${x#persistent-path=}" ;;
            union=*)
                export UNIONFS="${x#union=}";;
            ip=*)
                STATICIP=${x#ip=}
                if [ "${STATICIP}" = "" ]; then
                    STATICIP="frommedia"
                fi
                export STATICIP ;;
            uuid=*)
                UUID=${x#uuid=} ;;
            ignore_uuid)
                UUID="" ;;
            live-media-path=*)
                LIVE_MEDIA_PATH="${x#live-media-path=}"
                export LIVE_MEDIA_PATH
                echo "export LIVE_MEDIA_PATH=\"$LIVE_MEDIA_PATH\"" >> /etc/casper.conf ;;
            toram)
                export TORAM="Yes" ;;
            todisk=*)
                export TODISK="${x#todisk=}" ;;
        esac
    done
    if [ "${UNIONFS}" = "" ]; then
        export UNIONFS="DEFAULT"
    fi
}

setup_unionfs() {
    image_directory="$1"
    rootmnt="$2"

    if [ "${UNIONFS}" = 'DEFAULT' ]; then
	for union in 'overlayfs' 'aufs' 'unionfs'
	do
            modprobe "${MP_QUIET}" -b ${union} || true
            if cut -f2 /proc/filesystems | grep -q "^${union}\$"; then
		UNIONFS="${union}"
		break
	    fi
	done
    fi
    if [ "${UNIONFS}" = 'DEFAULT' -a -x /bin/unionfs-fuse ]; then
	UNIONFS="unionfs-fuse"
    fi
    # If all else fails fall back to aufs.
    if [ "${UNIONFS}" = 'DEFAULT' ]; then
	UNIONFS='aufs'
    fi

    # run-init can't deal with images in a subdir, but we're going to
    # move all of these away before it runs anyway.  No, we're not,
    # put them in / since move-mounting them into / breaks mono and
    # some other apps.

    croot="/"

    # Let's just mount the read-only file systems first
    rofsstring=""
    rofslist=""
    if [ "${UNIONFS}" = "aufs" ]; then
        roopt="rr"
    elif [ "${UNIONFS}" = "unionfs-fuse" ]; then
        roopt="RO"
    else
        roopt="ro"
    fi

    mkdir -p "${croot}"
    for image_type in "ext2" "squashfs" "dir" ; do
        for image in "${image_directory}"/*."${image_type}"; do
            imagename=$(basename "${image}")
            if [ -d "${image}" ]; then
                # it is a plain directory: do nothing
                rofsstring="${image}=${roopt}:${rofsstring}"
                rofslist="${image} ${rofslist}"
            elif [ -f "${image}" ]; then
                backdev=$(get_backing_device "$image")
                fstype=$(get_fstype "${backdev}")
                if [ "${fstype}" = "unknown" ]; then
                    panic "Unknown file system type on ${backdev} (${image})"
                fi
                mkdir -p "${croot}/${imagename}"
                mount -t "${fstype}" -o ro,noatime "${backdev}" "${croot}/${imagename}" || panic "Can not mount $backdev ($image) on ${croot}/${imagename}" && rofsstring="${croot}/${imagename}=${roopt}:${rofsstring}" && rofslist="${croot}/${imagename} ${rofslist}"
            fi
        done
    done
    rofsstring=${rofsstring%:}

    mkdir -p /cow
    cowdevice="tmpfs"
    cow_fstype="tmpfs"
    cow_mountopt="rw,noatime,mode=755"

    mount -t ${cow_fstype} -o ${cow_mountopt} ${cowdevice} /cow || panic "Can not mount $cowdevice on /cow"

    case ${UNIONFS} in
        unionfs-fuse)
            (ulimit -n 16384; unionfs-fuse -o cow -o noinitgroups -o default_permissions -o allow_other -o use_ino -o suid /cow=RW:$rofsstring "$rootmnt" || panic "${UNIONFS} mount failed")
            mkdir -p /dev/.initramfs/varrun
            pidof unionfs-fuse >> /dev/.initramfs/varrun/sendsigs.omit || true
            ;;
        aufs|unionfs)
            echo ########################################################################
            echo "mount -t ${UNIONFS} -o noatime,dirs=/cow=rw:$rofsstring ${UNIONFS} \"$rootmnt\""
            echo ########################################################################
            mount -t ${UNIONFS} -o noatime,dirs=/cow=rw:$rofsstring ${UNIONFS} "$rootmnt" || panic "${UNIONFS} mount failed"
            ;;
	overlayfs)
	    # Mount the layers pairwise from the bottom onto rootmnt,
	    # for the second and later layers rootmnt forms the lower layer.
	    mounts=""
	    for mount in /cow $rofslist
	    do
		mounts="$mount $mounts"
	    done
	    lower=""
	    for mount in $mounts
	    do
		if [ "$lower" = "" ]; then
		    lower="$mount"
		    continue
		fi
		mount -t overlayfs -o "upperdir=$mount,lowerdir=$lower" \
		    "$mount" "$rootmnt"
		lower="$rootmnt"
	    done
	    ;;
    esac

    # Adding other custom mounts
    if [ -n "${PERSISTENT}" ]; then
        # directly mount /home
        # FIXME: add a custom mounts configurable system
        homecow=$(find_cow_device "${home_persistence}" )
        if [ -b "${homecow}" ]; then
            mount -t $(get_fstype "${homecow}") -o rw,noatime "${homecow}" "${rootmnt}/home"
            export HOMEMOUNTED=1 # used to proper calculate free space in do_snap_copy()
        else
            [ "$quiet" != "y" ] && log_warning_msg "Unable to find the persistent home medium"
        fi
        # Look for other snapshots to copy in
        try_snap "${root_snapshot_label}" "${rootmnt}" "ROOT"
        try_snap "${home_snapshot_label}" "${rootmnt}/home" "HOME"
    fi

    if [ -n "${SHOWMOUNTS}" ]; then
        for d in ${rofslist}; do
            mkdir -p "${rootmnt}/${LIVE_MEDIA_PATH}/${d##*/}"
            case d in
                *.dir) # do nothing # mount -o bind "${d}" "${rootmnt}/${LIVE_MEDIA_PATH}/${d##*/}"
                    ;;
                *)
                    if [ "${UNIONFS}" = unionfs-fuse ]; then
                        mount -o bind "${d}" "${rootmnt}/${LIVE_MEDIA_PATH}/${d##*/}"
                    else
                        mount -o move "${d}" "${rootmnt}/${LIVE_MEDIA_PATH}/${d##*/}"
                    fi
                    ;;
            esac
        done
        # shows cow fs on /cow for use by casper-snapshot
        mkdir -p "${rootmnt}/cow"
        mount -o bind /cow "${rootmnt}/cow"
    fi

    # move the first mount; no head in busybox-initramfs
    for d in $(mount -t squashfs | cut -d\  -f 3); do
        mkdir -p "${rootmnt}/rofs"
        if [ "${UNIONFS}" = unionfs-fuse ]; then
            mount -o bind "${d}" "${rootmnt}/rofs"
        else
            mount -o move "${d}" "${rootmnt}/rofs"
        fi
        break
    done
}

# make /root available again:


mkdir -p /nfs/root.dir
mount -o move /root /nfs/root.dir


casper_parse_cmdline

setup_unionfs /nfs /root

echo "proc     /proc           proc    defaults 0 0" > /root/etc/fstab
echo "/dev/nfs /               nfs     defaults 0 0" >> /root/etc/fstab
echo "none     /tmp            tmpfs   defaults 0 0" >> /root/etc/fstab
echo "none     /var/run        tmpfs   defaults 0 0" >> /root/etc/fstab
echo "none     /var/lock       tmpfs   defaults 0 0" >> /root/etc/fstab
echo "none     /var/tmp        tmpfs   defaults 0 0" >> /root/etc/fstab

echo "iface eth0 inet manual" >> /root/etc/network/interfaces

chroot ${rootmnt} dpkg --purge network-manager-gnome
chroot ${rootmnt} dpkg --purge network-manager

echo "autologin=admunix" > /root/etc/lxdm/default.conf
