#!/bin/bash
# repo/install/initrd-src/files/usr/local/bin/setup
# Run the AM·OS setup wizard from the mounted ISO.
export PATH=/bin:/sbin:/usr/bin:/usr/sbin

# --- Block 1: ensure the ISO is mounted at /mnt ---
if ! mountpoint -q /mnt 2>/dev/null || [ ! -x /mnt/install/setup.sh ]; then
    echo "ISO not mounted at /mnt. Attempting to mount..." >&2
    for dev in /dev/sr0 /dev/sr1 /dev/sr2 /dev/cdrom \
               /dev/sda /dev/sdb /dev/sdc /dev/vda /dev/vdb; do
        [ -b "$dev" ] || continue
        fstype=$(blkid -s TYPE -o value "$dev" 2>/dev/null || true)
        [ "$fstype" = "iso9660" ] || continue
        mount -t iso9660 -o ro "$dev" /mnt 2>/dev/null || continue
        [ -d /mnt/install ] && break
        umount /mnt 2>/dev/null || true
    done
fi

if [ ! -x /mnt/install/setup.sh ]; then
    echo "ERROR: setup.sh not found on /mnt." >&2
    exit 1
fi


# --- Block 2: make /mnt/install writable via tmpfs bind-mount ---
# --- Development convenience: writable /mnt/install via tmpfs ---
# run setup once at the console, then SSH in and edit /mnt/install/install.sh freely". 
#If you forget, the write attempt fails with Read-only file system and you know to run setup once.
# The ISO is read-only. Copy /mnt/install into a tmpfs and bind-mount
# it back over the original path so scripts can be edited in place
# without rebuilding the ISO. Changes survive only until reboot.
if mountpoint -q /mnt && [ -d /mnt/install ] && [ ! -w /mnt/install ]; then
    if [ ! -d /tmp/install-rw ]; then
        mkdir -p /tmp/install-rw
        cp -a /mnt/install/. /tmp/install-rw/
    fi
    if mount --bind /tmp/install-rw /mnt/install 2>/dev/null; then
        echo "Note: /mnt/install is a writable tmpfs copy."
        echo "      Edits do NOT survive reboot."
    else
        echo "WARN: could not make /mnt/install writable." >&2
    fi
fi

exec /mnt/install/setup.sh "$@"