#!/usr/bin/env bash
# fleet-bootstrap step-0 loader "go" — static, public, auditable once.
# This file contains zero credentials by design.
#
# Run shapes:
#   USB:        sudo bash /run/media/$USER/FLEETBOOT/go
#   Passphrase: curl -fsSL https://bootstrap.morannon.xyz/go -o /tmp/go
#               sudo bash /tmp/go
#
# Flow: ensure age (distro-aware) -> locate key on the FLEETBOOT stick
# (else interactive passphrase) -> fetch blob -> decrypt -> sanity-check
# -> exec payload. Blob and payload are removed on every exit path.

set -euo pipefail

# Env overrides (test hooks; defaults are the production values)
BOOTSTRAP_URL="${BOOTSTRAP_URL:-https://bootstrap.morannon.xyz}"
BOOTSTRAP_BLOB="${BOOTSTRAP_BLOB:-/e/latest.age}"
BLOB_FILE="/tmp/fleet-bootstrap.age"
PAYLOAD_FILE="/tmp/fleet-bootstrap.sh"

cleanup() {
    rm -f "$BLOB_FILE" "$PAYLOAD_FILE"
}
trap cleanup EXIT

# Colors (disabled if not a terminal)
if [ -t 1 ]; then
    GREEN='\033[0;32m'; YELLOW='\033[1;33m'; RED='\033[0;31m'
    BLUE='\033[0;34m'; BOLD='\033[1m'; NC='\033[0m'
else
    GREEN=''; YELLOW=''; RED=''; BLUE=''; BOLD=''; NC=''
fi

info()  { printf "${GREEN}[OK]${NC} %s\n" "$*"; }
warn()  { printf "${YELLOW}[!]${NC} %s\n" "$*"; }
error() { printf "${RED}[X]${NC} %s\n" "$*"; }
header(){ printf "\n${BOLD}${BLUE}── %s ──${NC}\n\n" "$*"; }

# ── Detect the real user (who invoked sudo) ─────────────────────
REAL_USER="${SUDO_USER:-${USER:-}}"
if [ -z "$REAL_USER" ]; then
    REAL_USER="$(logname 2>/dev/null || true)"
fi

# ── Step 1: ensure age is installed ─────────────────────────────
if command -v age >/dev/null 2>&1; then
    info "age is available"
else
    header "Installing age"
    if command -v apt-get >/dev/null 2>&1; then
        apt-get update -qq
        apt-get install -y -qq age >/dev/null
    elif command -v dnf >/dev/null 2>&1; then
        dnf install -y -q age >/dev/null
    elif command -v pacman >/dev/null 2>&1; then
        pacman -S --needed --noconfirm age >/dev/null
    else
        error "Unsupported distro: no pacman/apt/dnf detected."
        error "Install age manually, then re-run this loader."
        exit 1
    fi
    info "age installed"
fi

# ── Step 2: locate the key on the FLEETBOOT stick ───────────────
# Env override (test harness only): skip USB discovery.
KEY_FILE="${BOOTSTRAP_KEY_FILE:-}"
if [ -z "$KEY_FILE" ]; then
    # Standard mount points; first one carrying the `key` file wins.
    for m in "/run/media/$REAL_USER/FLEETBOOT" \
             "/media/$REAL_USER/FLEETBOOT" \
             "/mnt/FLEETBOOT"; do
        if [ -f "$m/key" ]; then
            KEY_FILE="$m/key"
            break
        fi
    done
fi

# ── Step 3: fetch the blob (download-then-run, never curl|bash) ─
header "Fetching bootstrap payload"
URL="${BOOTSTRAP_URL}${BOOTSTRAP_BLOB}"
info "Downloading ${URL}"
curl -fsSL "$URL" -o "$BLOB_FILE"

# ── Step 4: decrypt ─────────────────────────────────────────────
header "Decrypting payload"
if [ -n "$KEY_FILE" ]; then
    info "Using the key file found on the USB stick"
    age -d -i "$KEY_FILE" -o "$PAYLOAD_FILE" "$BLOB_FILE"
else
    info "No USB key found — passphrase mode"
    age -d -o "$PAYLOAD_FILE" "$BLOB_FILE"
fi

# ── Step 5: sanity-check, then exec ─────────────────────────────
if ! head -n 1 "$PAYLOAD_FILE" | grep -q '^#!/'; then
    error "Decrypted payload is not a shell script (first line is not #!/)."
    exit 1
fi

rm -f "$BLOB_FILE"   # blob no longer needed; payload replaces this process
exec bash "$PAYLOAD_FILE"
