#!/bin/bash
# Copyright 2026 ANNE Media - https://anne.media
# All rights reserved.
#
# Redistribution and use of this script, with or without modification, is
# permitted provided that the following conditions are met:
#
# 1. Redistributions of this script must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#
#  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
#  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
#  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO
#  EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
#  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
#  OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
#  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
#  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
#  ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# AM·OS boot prompt. Runs from /init with the ISO not yet mounted.
#
# Verifies the ISO-wide CHECKSUMS.md5 before doing anything else. The
# GPG fingerprint is pinned at build time, so a tampered ISO that ships
# its own key, manifest, and signature is rejected.

export PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin

GPG_FPR="@GPG_FPR@"

mount_iso() {
    mountpoint -q /mnt 2>/dev/null && return 0
    local dev fstype
    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 ] && return 0
        umount /mnt 2>/dev/null || true
    done
    return 1
}

verify_iso() {
    local mnt=/mnt

    [ -f "$mnt/AMOS-GPG-KEY" ]    || { echo "missing: $mnt/AMOS-GPG-KEY"; return 1; }
    [ -f "$mnt/CHECKSUMS.md5" ]    || { echo "missing: $mnt/CHECKSUMS.md5"; return 1; }
    [ -f "$mnt/CHECKSUMS.md5.asc" ] || { echo "missing: $mnt/CHECKSUMS.md5.asc"; return 1; }

    local gnupg
    gnupg=$(mktemp -d); chmod 700 "$gnupg"

    # FIX: Disable keyboxd and gpg-agent for this temporary keyring.
    # This prevents GnuPG from trying to spawn daemons in the initrd.
    echo "#use-keyboxd" > "$gnupg/common.conf"
    echo "disable-dirmngr" >> "$gnupg/gpg.conf"

    # FIX: Add --batch --no-tty so gpg doesn't try to read from the console
    if ! GNUPGHOME="$gnupg" gpg --batch --no-tty --quiet --import "$mnt/AMOS-GPG-KEY" 2>/dev/null; then
        rm -rf "$gnupg"; echo "cannot import AMOS-GPG-KEY"; return 1
    fi

    local actual
    actual=$(GNUPGHOME="$gnupg" gpg --with-colons --list-keys 2>/dev/null \
        | awk -F: '/^fpr:/ {print $10; exit}')
    if [ "$actual" != "$GPG_FPR" ]; then
        rm -rf "$gnupg"
        echo "key fingerprint mismatch"
        echo "  expected: $GPG_FPR"
        echo "  actual:   $actual"
        return 1
    fi

    if ! GNUPGHOME="$gnupg" gpg --quiet --verify \
            "$mnt/CHECKSUMS.md5.asc" "$mnt/CHECKSUMS.md5" 2>/dev/null; then
        rm -rf "$gnupg"; echo "manifest signature invalid"; return 1
    fi

    rm -rf "$gnupg"

    if ! ( cd "$mnt" && tail +13 CHECKSUMS.md5 | md5sum -c --quiet - > /tmp/verify.out 2>&1 ); then
        echo "checksum mismatch"
        head -20 /tmp/verify.out
        return 1
    fi

    return 0
}

mount_iso || true

VERIFY_OK=0
if mountpoint -q /mnt 2>/dev/null; then
    echo
    echo "  Verifying ISO integrity..."
    if verify_iso; then
        VERIFY_OK=1
        echo "  Verified."
    else
        echo
        echo "  ISO verification FAILED. See above."
        echo "  This means the installation media has been tampered with,"
        echo "  or this is a development ISO whose checksums are stale."
        echo
        printf "  Proceed anyway? [y/N] "
        read -r ans
        case "$ans" in
            y|Y) VERIFY_OK=1 ;;
            *)   exec /bin/bash -l ;;
        esac
    fi
fi

echo
echo "  AM·OS installer media"
echo
echo "  Press ENTER to begin setup, or ESC for a shell."
echo "  Setup starts automatically in 30 seconds."
echo

timeout=30
for i in $(seq "$timeout" -1 1); do
    printf '\r  Auto-starting setup in %2d s  ' "$i"
    if read -t 1 -n 1 -s key; then
        printf '\r                                   \r'
        case "$key" in
            $'\e') exec /bin/bash -l ;;
            *)     break ;;
        esac
    fi
done
printf '\r                                   \r'

if [ -x /mnt/install/setup.sh ]; then
    exec /mnt/install/setup.sh
fi

echo "ERROR: /mnt/install/setup.sh not found. Dropping to a shell."
exec /bin/bash -l
