#!/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
    # systemd/mount.c guarantees that /run/initramfs/* mounts persist
    mkdir -p /run/initramfs/rofs /run/initramfs/cow
    mount -t tmpfs -o mode=0755 tmpfs /run/initramfs/cow
    if [ "$LTSP_NBD_TO_RAM" = "true" ]; then
        umount ${rootmnt}
        dd if=/dev/nbd0 of=/run/initramfs/cow/.rofsimage.img bs=1024k
        nbd-client -d /dev/nbd0
        mount -o loop /run/initramfs/cow/.rofsimage.img /run/initramfs/rofs
    else
        mount -o move ${rootmnt} /run/initramfs/rofs
    fi
    if modprobe overlay; then
        UNION_TYPE=overlay
        UNION_OPTS="upperdir=/run/initramfs/cow/up,lowerdir=/run/initramfs/rofs,workdir=/run/initramfs/cow/work"
        mkdir -p /run/initramfs/cow/up /run/initramfs/cow/work
    elif modprobe overlayfs; then
        UNION_TYPE=overlayfs
        UNION_OPTS="upperdir=/run/initramfs/cow,lowerdir=/run/initramfs/rofs"
    elif modprobe aufs; then
        UNION_TYPE=aufs
        UNION_OPTS="dirs=/run/initramfs/cow=rw:/run/initramfs/rofs=ro"
    else
        panic "Could not load neither overlayfs nor aufs."
    fi
    mount -t ${UNION_TYPE} -o ${UNION_OPTS} ${UNION_TYPE} ${rootmnt}
fi

# Copy networking configuration to the root file system
mkdir -p "$rootmnt/run/ltsp/"
for netconf in /tmp/net-*.conf /run/net-*.conf; do
    if [ -f "$netconf" ]; then
        cp "$netconf" "$rootmnt/run/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
