#!/bin/sh
# AeroOS live initramfs init.
# Built-in kernel support is assumed for: iso9660, squashfs, overlay, loop.
# Finds the live medium, mounts the squashfs read-only, layers a tmpfs via
# overlayfs, then switches root into the real AeroOS system (systemd).
/bin/busybox --install -s /bin 2>/dev/null
[ -c /dev/console ] && exec </dev/console >/dev/console 2>&1

mount -t proc     proc     /proc
mount -t sysfs    sysfs    /sys
mount -t devtmpfs devtmpfs /dev 2>/dev/null

LABEL="@@ISO_LABEL@@"
SQUASH="/run/iso/LiveOS/aeros.squashfs"

echo "AeroOS: locating live medium (label $LABEL)..."
mkdir -p /run/iso /run/sqfs /run/overlay /sysroot

# wait for the CD/USB to appear, then mount by label
dev=""
for try in $(seq 1 30); do
    for d in /dev/sr0 /dev/sr1 $(ls /dev/sd? /dev/sd?? /dev/vd? 2>/dev/null); do
        [ -b "$d" ] || continue
        if blkid "$d" 2>/dev/null | grep -q "LABEL=\"$LABEL\""; then dev="$d"; break; fi
    done
    [ -n "$dev" ] && break
    sleep 0.5
done

[ -n "$dev" ] || { echo "AeroOS: live medium not found"; exec sh; }
echo "AeroOS: live medium = $dev"
mount -t iso9660 -o ro "$dev" /run/iso || { echo "iso mount failed"; exec sh; }

# mount the squashfs (read-only lower layer)
mount -t squashfs -o ro,loop "$SQUASH" /run/sqfs || { echo "squashfs mount failed"; exec sh; }

# writable overlay in RAM
mount -t tmpfs tmpfs /run/overlay
mkdir -p /run/overlay/upper /run/overlay/work
mount -t overlay overlay \
    -o lowerdir=/run/sqfs,upperdir=/run/overlay/upper,workdir=/run/overlay/work \
    /sysroot || { echo "overlay mount failed"; exec sh; }

# move the already-mounted vkfs into the new root and switch
mkdir -p /sysroot/run/iso
mount --move /run/iso /sysroot/run/iso 2>/dev/null
for fs in proc sys dev; do mount --move /$fs /sysroot/$fs 2>/dev/null; done

echo "AeroOS: switching root -> systemd"
exec switch_root /sysroot /sbin/init
