#!/bin/sh
# Nimux pre-systemd boot

export ROOT_DEV=/dev/ram0
export RUN_NIMUX=/run/nimux
export ROOTFS_ORIG=$RUN_NIMUX/rootfs.orig
export NIMUX_OVERLAY=$RUN_NIMUX/overlay

# create the minimal required mount
/bin/echo "[init] Cmdline:" "$@"
/bin/echo "[init] perform early mounts"
/bin/mount -t proc proc /proc
/bin/mount -t sysfs sysfs /sys
/bin/mount -t devtmpfs devtmpfs /dev
/bin/mount -t tmpfs tmpfs /run
/bin/mount -t tmpfs tmpfs /mnt

# mount root on a future accesable place
/bin/echo "[init] re-mount rootfs"
/bin/mkdir -p $ROOTFS_ORIG
/bin/mount -t squashfs -o ro $ROOT_DEV $ROOTFS_ORIG
/bin/mount --make-rprivate $ROOTFS_ORIG

# overlay the /var directory with a volatile tmpfs
/bin/echo "[init] overlay /var"
export VAR_LOWER=$ROOTFS_ORIG/var
export VAR_UPPER=$NIMUX_OVERLAY/var/upper
export VAR_WORK=$NIMUX_OVERLAY/var/work

/bin/mkdir -p $VAR_UPPER $VAR_WORK
/bin/mount -t overlay overlay-var -o lowerdir=$VAR_LOWER,upperdir=$VAR_UPPER,workdir=$VAR_WORK /var

# ovelay /etc and patch with persistant storage 
# we don´t overlay on persistent storage, because this will cause bootfailures
# when the lower dir (rootfs.squashfs) is updated by a future release of Numix
/bin/echo "[init] overlay /etc"
export ETC_LOWER=$ROOTFS_ORIG/etc
export ETC_UPPER=$NIMUX_OVERLAY/etc/upper
export ETC_WORK=$NIMUX_OVERLAY/etc/work

/bin/mkdir -p $ETC_UPPER $ETC_WORK
/bin/mount -t overlay overlay-etc -o lowerdir=$ETC_LOWER,upperdir=$ETC_UPPER,workdir=$ETC_WORK /etc

# import zpool (this will also mount etc & home)
/bin/echo "[init] import zpool"
/sbin/zpool import nimux-zfs

# update etc dir with persitent data
export ETC_PERSIST=$NIMUX_OVERLAY/etc/persist
/bin/echo "[init] update /etc with persistant data"
/bin/echo "[init] /etc persist dir: " $ETC_PERSIST
/bin/cp -R $ETC_PERSIST/* /etc

# hand over to systemd
/bin/echo "[init] handover control to systemd"
exec /usr/lib/systemd/systemd

# we shouldn´t get to here
echo "[init] ERROR: switch_root failed!" >&2
export PS1="\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\] (init-rescue)# "
exec sh
