#!/bin/sh
# Keru live ISO init — jumps straight into the installer.
#
# The live ISO carries only the installer. On boot this script:
#   1. mounts the virtual filesystems
#   2. attaches the read-only installer root (squashfs, plain initramfs, or
#      an unattached block device)
#   3. execs installer/install.sh on the console — so you boot, choose, and it
#      crafts and installs the system. No shell prompt in the way.
#   4. if the installer exits (e.g. you declined to build), drops to an
#      emergency shell instead of leaving you stranded.
#
# Ultra-minimal by design: /bin/sh is busybox. No init system in the live env.

# ---- console -----------------------------------------------------------
# Redirect the console early so messages land where you can see them.
CONSOLE="${console:-/dev/tty1}"
exec <"$CONSOLE" >"$CONSOLE" 2>"$CONSOLE"

# ---- virtual filesystems ----------------------------------------------
mount -t proc     proc /proc 2>/dev/null
mount -t sysfs    sys  /sys  2>/dev/null
mount -t devtmpfs dev  /dev  2>/dev/null || (mkdir -p /dev && mount -t tmpfs dev /dev 2>/dev/null)
mkdir -p /dev/pts /dev/shm
mount -t devpts   devpts /dev/pts 2>/dev/null
mount -t tmpfs    tmpfs  /dev/shm  2>/dev/null

# ---- locate the installer root ----------------------------------------
# Where the installer payload lives. Tried in order:
#   1. $root — whatever the kernel booted (a squashfs / overlay already handled
#      by an initramfs that then hands off here).
#   2. a squashfs node named *.sfs on a known device (label=KERU).
#   3. nothing — the installer is already on the root we're running from.
case "${root:-}" in
    /dev/*)
        # re-mount as the boot-time root: cannot pivot here, so use it directly
        /bin/busybox mount -o move / "$root" 2>/dev/null || true
        ;;
    '')
        for _dev in /dev/disk/by-label/KERU*; do
            [ -e "$_dev" ] || continue
            _node="$(readlink -f "$_dev")"
            mount "$_node" /squash 2>/dev/null || continue
            INSTALLER=/squash
            break
        done
        ;;
esac
INSTALLER="${INSTALLER:-/}"

# ---- launch the installer ---------------------------------------------
if [ -e "$INSTALLER/installer/install.sh" ]; then
    printf '\n[ keru ] booting installer...\n'
    cd "$INSTALLER" && exec /bin/sh "$INSTALLER/installer/install.sh"
fi

# If we land here the installer is missing or returned. Never strand someone:
# fall back to an interactive rescue shell.
printf '\n[ keru ] installer not found or exited.\n'
printf '[ keru ] dropping to an emergency shell. (installer path: %s)\n' "$INSTALLER"
exec /bin/sh
