#!/bin/sh

# We support two methods to call the init-ltsp.d scripts.
# The first method is to pass "ltsp" in the kernel command line, which calls
# the scripts with `chroot` while still in the initramfs, i.e. at the end of
# this script.
# The second is to pass "init=/sbin/init-ltsp", which will execute the scripts
# in the real system and chain to /sbin/init after that.

for x in $(cat /proc/cmdline); do
    case "$x" in
        init=/sbin/init-ltsp)
            LTSP_BOOT=true
            break
            ;;
        ltsp)
            LTSP_BOOT=true
            CALL_SCRIPTS=true
            break
            ;;
    esac
done

test -n "$LTSP_BOOT" || exit

[ -z "${rootmnt}" ] && panic "rootmnt unknown in init-bottom"
[ -d "${rootmnt}/proc" ] || panic "rootmnt not mounted in init-bottom"
# mount writeable filesystems if / is not already mounted writeable.
if ! chroot ${rootmnt} /usr/bin/test -w "/" ; then
    mkdir -p /rofs /cow
    mount -t tmpfs -o mode=0755 tmpfs /cow
    if [ "$LTSP_NBD_TO_RAM" = "true" ]; then
        umount ${rootmnt}
        dd if=/dev/nbd0 of=/cow/.rofsimage.img bs=1024k
        nbd-client -d /dev/nbd0
        mount -o loop /cow/.rofsimage.img /rofs
    else
        mount -o move ${rootmnt} /rofs
    fi
    if modprobe overlay; then
        UNION_TYPE=overlay
        UNION_OPTS="upperdir=/cow/up,lowerdir=/rofs,workdir=/cow/work"
        mkdir -p /cow/up /cow/work
    elif modprobe overlayfs; then
        UNION_TYPE=overlayfs
        UNION_OPTS="upperdir=/cow,lowerdir=/rofs"
    elif modprobe aufs; then
        UNION_TYPE=aufs
        UNION_OPTS="dirs=/cow=rw:/rofs=ro"
    else
        . /scripts/functions
        panic "Could not load neither overlayfs nor aufs."
    fi
    mount -t ${UNION_TYPE} -o ${UNION_OPTS} ${UNION_TYPE} ${rootmnt}
    for dir in /rofs /cow ; do
        mkdir -p ${rootmnt}${dir}
    	mount -o move ${dir} ${rootmnt}${dir}
    done
fi

# Copy networking configuration to the root file system
mkdir -p "$rootmnt/var/cache/ltsp/"
for netconf in /tmp/net-*.conf /run/net-*.conf; do
    if [ -f "$netconf" ]; then
        cp "$netconf" "$rootmnt/var/cache/ltsp/"
    fi
done

if [ -n "$CALL_SCRIPTS" ]; then
    mount -o bind /proc "$rootmnt/proc"
    EXEC_INIT=false chroot "$rootmnt" /sbin/init-ltsp
    umount "$rootmnt/proc"
fi
