#!/bin/sh

# We support two methods to call the init-ltsp.d scripts.
# Either directly by passing "init=/sbin/init-ltsp" in the kernel cmdline,
# or indirectly with "ltsp.init=xxx", where the LTSP initramfs scripts
# need to take care so that the specified init is called.

PREREQ=""

prereqs()
{
    echo "$PREREQ"
}

case "$1" in
    prereqs)
        prereqs
        exit 0
        ;;
esac

grep -qs "init=/sbin/init-ltsp" /proc/cmdline || exit 0
. /scripts/functions

[ -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
        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

ltspinit=$(sed -n 's/.*ltsp.init=\([^[:space:]]*\).*/\1/p' /proc/cmdline)
if [ -n "$ltspinit" ]; then
    echo "init=$ltspinit" >> /conf/param.conf
fi
