#!/usr/bin/env bash
# SPDX-License-Identifier: LicenseRef-CMSD-1.0
# Copyright (c) 2026 CyberMind — Gérald Kerma <devel@cybermind.fr>
# Source-Disclosed License — All rights reserved except as expressly granted.
# See LICENCE-CMSD-1.0.md for terms.
# ══════════════════════════════════════════════════════════════════
#  SecuBox-DEB :: secubox-flash-emmc
#  Flash SecuBox image to EspressoBin V7 eMMC
#  CyberMind — https://cybermind.fr
# ══════════════════════════════════════════════════════════════════
set -euo pipefail

VERSION="1.1.0"
SCRIPT_NAME="secubox-flash-emmc"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
CYAN='\033[0;36m'
BOLD='\033[1m'
NC='\033[0m'

# Default paths
DEFAULT_IMAGE="/secubox/secubox-ebin-v7.img.gz"
LOG_FILE="/var/log/secubox-flash.log"

# Auto-detect eMMC device (has boot0 partition - unique to eMMC, not SD cards)
detect_emmc() {
    local dev
    for dev in /dev/mmcblk0 /dev/mmcblk1 /dev/mmcblk2; do
        # eMMC has boot0 partition (block device), SD cards don't
        if [[ -b "${dev}boot0" ]]; then
            echo "$dev"
            return 0
        fi
    done
    return 1
}

# ── Écriture en flux vérifiée (#3233) ─────────────────────────────
# Sur 1 Go de RAM (ESPRESSObin), l'image ne tient pas en mémoire : elle arrive sur l'entrée standard et s'écrit au fil
# de l'eau. La signature (clé publique) et l'empreinte SHA-256 du flux COMPRESSÉ sont calculées pendant l'écriture ;
# elles ne se concluent qu'à la fin. La TÊTE (2 premiers Mo : MBR de protection, GPT primaire, début de p1) est gardée
# de côté et n'est écrite qu'APRÈS validation : une écriture interrompue de quelque façon que ce soit (Ctrl+C, SSH
# coupé, OOM, courant coupé, serveur figé) laisse un disque sans table de partitions, donc rien d'amorçable. L'ancienne
# tête et l'ancienne GPT de secours sont effacées AVANT la première écriture.
TETE_MO=2

invalide_cible() { # CIBLE — début (table, chargeur) et fin (GPT de secours) remis à zéro ; code ≠ 0 si impossible
    local c="$1" taille n rc=0
    if [ -b "$c" ]; then
        taille="$(blockdev --getsize64 "$c")" || return 1
    else
        taille="$(stat -c %s "$c")" || return 1          # cible ordinaire : bancs d'essai seulement
    fi
    [ "${taille:-0}" -gt 0 ] || return 1
    n=$(( taille / 1048576 )); [ "$n" -gt 64 ] && n=64; [ "$n" -ge 1 ] || n=1
    dd if=/dev/zero of="$c" bs=1M count="$n" conv=fsync,notrunc status=none || rc=1
    if [ "$taille" -gt $(( 128 * 1048576 )) ]; then
        dd if=/dev/zero of="$c" bs=1M seek=$(( taille / 1048576 - 1 )) count=1 conv=fsync,notrunc status=none || rc=1
    fi
    sync
    return "$rc"
}

ecrit_corps() { # CIBLE FICHIER_TETE — les TETE_MO premiers Mo vont dans FICHIER_TETE, le reste sur la cible à leur suite
    dd of="$2" bs=1M count="$TETE_MO" iflag=fullblock status=none || return 1
    # Vers l'eMMC : écriture DIRECTE, débit régulier. Par le cache, une carte à 1 Go accumulait des pages sales puis
    # cessait de lire le flux pendant les vidages (> 60 s) et le téléchargement était coupé (banc du 2026-10-28).
    # exec : arrêter le flux arrête ce dd.
    if [ -b "$1" ]; then
        exec dd of="$1" bs=1M seek="$TETE_MO" iflag=fullblock oflag=direct conv=fsync,notrunc status=none
    fi
    exec dd of="$1" bs=1M seek="$TETE_MO" conv=fsync,notrunc status=none
}

# Code : 0 écrite et vérifiée ; 1 refusée, cible invalidée ; 2 paramètres refusés, rien touché ; 3 refusée et
# INVALIDATION ÉCHOUÉE (ne pas démarrer sur la cible).
ecrit_flux_verifie() { # CIBLE FORMAT(gz|xz) SIGNATURE CLE_PUB SHA256 — flux compressé sur l'entrée standard
    local cible="$1" format="$2" sig="$3" pub="$4" attendu="$5" t p_sig p_sha p_flux v somme dec m="" rc=0
    case "$format" in
        gz) dec="gzip" ;;
        xz) dec="xz" ;;
        *) echo "format de flux inconnu : $format (gz ou xz)" >&2; return 2 ;;
    esac
    [ -s "$sig" ] && [ -s "$pub" ] && [[ "$attendu" =~ ^[0-9a-f]{64}$ ]] \
        || { echo "signature, clé publique ou empreinte manquante : rien n'est écrit" >&2; return 2; }
    t="$(mktemp -d)" || return 1
    invalide_cible "$cible" || { rm -rf "$t"; echo "cible impossible à préparer : rien n'est écrit" >&2; return 3; }
    mkfifo "$t/sig" "$t/sha"
    openssl dgst -sha256 -verify "$pub" -signature "$sig" < "$t/sig" > "$t/verdict" 2>&1 & p_sig=$!
    sha256sum < "$t/sha" > "$t/somme" & p_sha=$!
    # Le flux tourne en tâche de fond (entrée standard gardée explicitement) : bash ne lance un trap qu'APRÈS la
    # commande au premier plan, mais `wait`, lui, est interrompu par le signal. Interruption (Ctrl+C, SSH coupé,
    # arrêt) : le flux est arrêté, la tête n'est pas écrite, et ce qui l'a été est effacé.
    # Trap posé AVANT de lancer le flux ; il distingue l'invalidation réussie (130) de l'invalidation ratée (3).
    p_flux=""
    trap 'if [ -n "$p_flux" ]; then pkill -TERM -P "$p_flux" 2>/dev/null; kill "$p_flux" 2>/dev/null; wait "$p_flux" 2>/dev/null; fi
          kill "$p_sig" "$p_sha" 2>/dev/null
          if invalide_cible "$cible"; then rc=130; m="cible invalidée"; else rc=3; m="INVALIDATION ÉCHOUÉE : ne pas démarrer sur la cible"; fi
          declare -F audit >/dev/null && audit "flux interrompu cible=$cible sha256=$attendu ($m)"
          rm -rf "$t"; echo "flux interrompu : $m" >&2; exit "$rc"' INT TERM HUP
    ( set +e; tee "$t/sig" "$t/sha" | "$dec" -dc | ecrit_corps "$cible" "$t/tete"; echo "${PIPESTATUS[*]}" > "$t/etats" ) 0<&0 &
    p_flux=$!
    set +e
    wait "$p_flux"
    local etats
    read -r -a etats < "$t/etats" 2>/dev/null || etats=(1 1 1)
    wait "$p_sig"; v=$?
    wait "$p_sha"
    somme="$(awk '{print $1}' "$t/somme" 2>/dev/null)"
    set -e
    if [ "${etats[0]}" -eq 0 ] && [ "${etats[1]}" -eq 0 ] && [ "${etats[2]}" -eq 0 ] && [ "$v" -eq 0 ] \
            && [ "$somme" = "$attendu" ] \
            && dd if="$t/tete" of="$cible" bs=1M conv=fsync,notrunc status=none; then
        trap - INT TERM HUP
        rm -rf "$t"
        sync
        return 0
    fi
    trap - INT TERM HUP
    rm -rf "$t"
    echo "flux refusé (tee=${etats[0]} ${dec}=${etats[1]} corps=${etats[2]} signature=$v empreinte=${somme:-?})" >&2
    invalide_cible "$cible" || { echo "INVALIDATION ÉCHOUÉE : ne pas démarrer sur la cible" >&2; return 3; }
    return 1
}

# Chargeable sans exécuter (tests) : SBX_FLASH_EMMC_SOURCE=1. EXÉCUTÉ avec cette variable, il refuse (code 2) : sortir
# en succès sans rien écrire ferait croire à l'appelant que l'eMMC est écrite.
if [[ -n "${SBX_FLASH_EMMC_SOURCE:-}" ]]; then
    if (return 0 2>/dev/null); then return 0; fi      # chargé par `source` : seul cas où `return` est permis
    echo "SBX_FLASH_EMMC_SOURCE est réservée aux tests : refus" >&2
    exit 2
fi

AUDIT=/var/log/secubox/netboot/audit.log
audit() { mkdir -p "$(dirname "$AUDIT")" 2>/dev/null && echo "$(date -Iseconds) flash-emmc $*" >> "$AUDIT" 2>/dev/null || true; }

EMMC_DEVICE=""

# Options
AUTO_MODE=0
DRY_RUN=0
NO_REBOOT=0
IMAGE_PATH=""
STDIN_FORMAT=""
SIG_FILE=""
PUB_FILE=""
SHA_ATTENDU=""

log()  { echo -e "${CYAN}[flash]${NC} $*"; echo "[$(date -Iseconds)] $*" >> "$LOG_FILE"; }
ok()   { echo -e "${GREEN}[  OK ]${NC} $*"; echo "[$(date -Iseconds)] OK: $*" >> "$LOG_FILE"; }
warn() { echo -e "${YELLOW}[WARN ]${NC} $*"; echo "[$(date -Iseconds)] WARN: $*" >> "$LOG_FILE"; }
err()  { echo -e "${RED}[FAIL ]${NC} $*" >&2; echo "[$(date -Iseconds)] FAIL: $*" >> "$LOG_FILE"; exit 1; }

usage() {
    cat << EOF
${BOLD}SecuBox eMMC Flasher v${VERSION}${NC}

${BOLD}USAGE:${NC}
    $SCRIPT_NAME [OPTIONS]

${BOLD}OPTIONS:${NC}
    -a, --auto          Non-interactive mode (no confirmations)
    -i, --image PATH    Path to image file (default: $DEFAULT_IMAGE)
    -d, --dry-run       Show what would be done without writing
    -n, --no-reboot     Don't reboot after successful flash
    -h, --help          Show this help message
    --stdin FMT --sig FICHIER --pub FICHIER --sha256 EMPREINTE
                        Image compressée (gz|xz) lue sur l'entrée standard, écrite en flux, signature et empreinte
                        vérifiées pendant l'écriture ; échec = eMMC invalidée. Exige --auto (#3233).

${BOLD}SAFETY:${NC}
    - Will NOT flash if currently running from eMMC
    - Verifies image integrity before flashing
    - Creates backup of partition table (if requested)

${BOLD}EXAMPLES:${NC}
    # Interactive flash with bundled image
    $SCRIPT_NAME

    # Automated flash for unattended installation
    $SCRIPT_NAME --auto --no-reboot

    # Flash custom image
    $SCRIPT_NAME --image /media/usb/custom-image.img.gz

EOF
    exit 0
}

# ── Parse arguments ─────────────────────────────────────────────────
while [[ $# -gt 0 ]]; do
    case "$1" in
        -a|--auto)      AUTO_MODE=1; shift ;;
        -i|--image)     IMAGE_PATH="$2"; shift 2 ;;
        -d|--dry-run)   DRY_RUN=1; shift ;;
        -n|--no-reboot) NO_REBOOT=1; shift ;;
        --stdin)        STDIN_FORMAT="$2"; shift 2 ;;
        --sig)          SIG_FILE="$2"; shift 2 ;;
        --pub)          PUB_FILE="$2"; shift 2 ;;
        --sha256)       SHA_ATTENDU="$2"; shift 2 ;;
        -h|--help)      usage ;;
        *) err "Unknown option: $1. Use --help for usage." ;;
    esac
done

if [[ -n "$STDIN_FORMAT" ]]; then
    # L'entrée standard porte l'image : aucune confirmation ne peut y être lue, c'est l'appelant qui la demande.
    [[ $AUTO_MODE -eq 1 ]] || err "--stdin exige --auto : la confirmation est demandée par l'appelant"
    [[ "$STDIN_FORMAT" == gz || "$STDIN_FORMAT" == xz ]] || err "--stdin : format gz ou xz attendu"
    [[ -s "$SIG_FILE" && -s "$PUB_FILE" ]] || err "--stdin exige --sig et --pub"
    [[ "$SHA_ATTENDU" =~ ^[0-9a-f]{64}$ ]] || err "--stdin exige --sha256 (64 caractères hexadécimaux)"
fi

# ── Safety checks ───────────────────────────────────────────────────

# Check if running as root
[[ $EUID -ne 0 ]] && err "This script must be run as root (sudo)"

# Detect boot device
BOOT_DEVICE=$(findmnt -no SOURCE / 2>/dev/null | sed 's/[0-9]*$//' | sed 's/p$//')
log "Boot device: $BOOT_DEVICE"

# Auto-detect eMMC device
if ! EMMC_DEVICE=$(detect_emmc); then
    err "eMMC device not found!

    Checked: /dev/mmcblk0, /dev/mmcblk1, /dev/mmcblk2
    Looking for: boot0, boot1, rpmb partitions (eMMC signature)

    This could mean:
    - No eMMC installed on this board
    - Kernel module not loaded (sdhci-xenon-esdhc)
    - Check 'lsblk' output for available devices"
fi

log "Detected eMMC: $EMMC_DEVICE"

# CRITICAL: Don't flash if running from eMMC
if [[ "$BOOT_DEVICE" == "$EMMC_DEVICE" ]] || [[ "$BOOT_DEVICE" == "${EMMC_DEVICE}p"* ]]; then
    err "SAFETY STOP: Currently booted from eMMC ($EMMC_DEVICE)!

    You cannot flash the eMMC while running from it.
    Please boot from USB drive first, then run this script."
fi

# Verify eMMC is accessible
if [[ ! -b "$EMMC_DEVICE" ]]; then
    err "eMMC device not accessible: $EMMC_DEVICE"
fi

# Aucune partition de l'eMMC montée ni en swap (#3233) : la garde du démarrage ne regarde que /.
if lsblk -nro MOUNTPOINTS "$EMMC_DEVICE" 2>/dev/null | grep -q . || lsblk -nro MOUNTPOINT "$EMMC_DEVICE" 2>/dev/null | grep -q . \
        || grep -q "^${EMMC_DEVICE}" /proc/swaps 2>/dev/null; then
    err "SAFETY STOP: une partition de $EMMC_DEVICE est montée ou en swap — la démonter avant d'écrire"
fi

# ── Mode flux (#3233) : gardes passées, écriture vérifiée au fil de l'eau ─
if [[ -n "$STDIN_FORMAT" ]]; then
    EMMC_SIZE_GB=$(( $(blockdev --getsize64 "$EMMC_DEVICE" 2>/dev/null || echo 0) / 1024 / 1024 / 1024 ))
    log "Flux ${STDIN_FORMAT} → ${EMMC_DEVICE} (${EMMC_SIZE_GB} GB), démarré depuis ${BOOT_DEVICE} : TOUT L'eMMC SERA EFFACÉ"
    if [[ $DRY_RUN -eq 1 ]]; then
        log "DRY RUN: aucune écriture"
        exit 0
    fi
    sync
    audit "flux debut cible=$EMMC_DEVICE format=$STDIN_FORMAT sha256=$SHA_ATTENDU"
    set +e
    ecrit_flux_verifie "$EMMC_DEVICE" "$STDIN_FORMAT" "$SIG_FILE" "$PUB_FILE" "$SHA_ATTENDU" 2>>"$LOG_FILE"
    rc=$?
    set -e
    case "$rc" in
        0) audit "flux ecrit cible=$EMMC_DEVICE sha256=$SHA_ATTENDU verdict=valide" ;;
        3) audit "flux refuse cible=$EMMC_DEVICE sha256=$SHA_ATTENDU invalidation=ECHEC"
           err "VÉRIFICATION ÉCHOUÉE et INVALIDATION ÉCHOUÉE : NE PAS démarrer sur l'eMMC ($EMMC_DEVICE) — détail : $LOG_FILE" ;;
        *) audit "flux refuse cible=$EMMC_DEVICE sha256=$SHA_ATTENDU invalidation=ok code=$rc"
           err "VÉRIFICATION ÉCHOUÉE (signature, empreinte ou flux interrompu) — eMMC invalidée, rien d'amorçable n'y reste ; détail : $LOG_FILE" ;;
    esac
    ok "Image écrite et vérifiée (signature et empreinte)"
    partprobe "$EMMC_DEVICE" 2>/dev/null || true
    if [[ $NO_REBOOT -eq 0 ]]; then
        log "Redémarrage dans 5 s"
        sleep 5
        systemctl reboot 2>/dev/null || reboot
    fi
    exit 0
fi

# ── Find image ──────────────────────────────────────────────────────

if [[ -n "$IMAGE_PATH" ]]; then
    [[ -f "$IMAGE_PATH" ]] || err "Image not found: $IMAGE_PATH"
elif [[ -f "$DEFAULT_IMAGE" ]]; then
    IMAGE_PATH="$DEFAULT_IMAGE"
else
    # Search for image in common locations
    for path in \
        /secubox/*.img.gz \
        /media/*/secubox/*.img.gz \
        /mnt/*/secubox/*.img.gz \
        /home/*/secubox/*.img.gz; do
        if [[ -f "$path" ]]; then
            IMAGE_PATH="$path"
            break
        fi
    done
fi

[[ -z "$IMAGE_PATH" ]] && err "No image file found. Use --image to specify path."
[[ -f "$IMAGE_PATH" ]] || err "Image not found: $IMAGE_PATH"

log "Image file: $IMAGE_PATH"

# ── Get image info ──────────────────────────────────────────────────

IMAGE_SIZE=$(stat -c%s "$IMAGE_PATH")
IMAGE_SIZE_MB=$((IMAGE_SIZE / 1024 / 1024))
log "Compressed image size: ${IMAGE_SIZE_MB} MB"

# Check for checksum file
CHECKSUM_FILE="${IMAGE_PATH%.gz}.sha256"
[[ -f "$CHECKSUM_FILE" ]] || CHECKSUM_FILE="${IMAGE_PATH}.sha256"
HAS_CHECKSUM=0
if [[ -f "$CHECKSUM_FILE" ]]; then
    HAS_CHECKSUM=1
    log "Checksum file found: $CHECKSUM_FILE"
fi

# Get eMMC size
EMMC_SIZE=$(blockdev --getsize64 "$EMMC_DEVICE" 2>/dev/null || echo "0")
EMMC_SIZE_GB=$((EMMC_SIZE / 1024 / 1024 / 1024))
log "eMMC size: ${EMMC_SIZE_GB} GB ($EMMC_DEVICE)"

# Estimate decompressed size (assume ~3x compression ratio)
EST_SIZE=$((IMAGE_SIZE * 3))
if [[ $EST_SIZE -gt $EMMC_SIZE ]] && [[ $EMMC_SIZE -gt 0 ]]; then
    warn "Image may be larger than eMMC capacity!"
    warn "Estimated: $((EST_SIZE / 1024 / 1024 / 1024))GB, eMMC: ${EMMC_SIZE_GB}GB"
fi

# ── Display summary ─────────────────────────────────────────────────

echo ""
echo -e "${BOLD}╔═══════════════════════════════════════════════════════════════╗${NC}"
echo -e "${BOLD}║            SecuBox eMMC Flasher v${VERSION}                      ║${NC}"
echo -e "${BOLD}╠═══════════════════════════════════════════════════════════════╣${NC}"
echo -e "${BOLD}║${NC}  Source Image : ${CYAN}$(basename "$IMAGE_PATH")${NC}"
echo -e "${BOLD}║${NC}  Image Size   : ${IMAGE_SIZE_MB} MB (compressed)"
echo -e "${BOLD}║${NC}  Checksum     : $([[ $HAS_CHECKSUM -eq 1 ]] && echo "${GREEN}Yes${NC}" || echo "${YELLOW}No${NC}")"
echo -e "${BOLD}╠═══════════════════════════════════════════════════════════════╣${NC}"
echo -e "${BOLD}║${NC}  Target Device: ${RED}${EMMC_DEVICE}${NC}"
echo -e "${BOLD}║${NC}  eMMC Size    : ${EMMC_SIZE_GB} GB"
echo -e "${BOLD}║${NC}  Boot Device  : ${GREEN}${BOOT_DEVICE}${NC} (safe, not eMMC)"
echo -e "${BOLD}╠═══════════════════════════════════════════════════════════════╣${NC}"
echo -e "${BOLD}║${NC}  ${RED}WARNING: ALL DATA ON eMMC WILL BE ERASED!${NC}"
echo -e "${BOLD}╚═══════════════════════════════════════════════════════════════╝${NC}"
echo ""

# ── Dry run exit ────────────────────────────────────────────────────

if [[ $DRY_RUN -eq 1 ]]; then
    log "DRY RUN: Would flash $IMAGE_PATH to $EMMC_DEVICE"
    log "DRY RUN: No changes made"
    exit 0
fi

# ── Confirmation ────────────────────────────────────────────────────

if [[ $AUTO_MODE -eq 0 ]]; then
    echo -e "${YELLOW}This will ERASE ALL DATA on the eMMC!${NC}"
    echo ""
    read -p "Type 'FLASH' to confirm, or anything else to cancel: " confirm
    if [[ "$confirm" != "FLASH" ]]; then
        log "Flash cancelled by user"
        echo "Cancelled."
        exit 1
    fi
else
    log "Auto mode enabled - skipping confirmation"
    sleep 2  # Brief pause in auto mode
fi

# ── Verify checksum (if available) ──────────────────────────────────

if [[ $HAS_CHECKSUM -eq 1 ]]; then
    log "Verifying image checksum..."
    EXPECTED=$(cat "$CHECKSUM_FILE" | awk '{print $1}')
    ACTUAL=$(sha256sum "$IMAGE_PATH" | awk '{print $1}')

    if [[ "$EXPECTED" == "$ACTUAL" ]]; then
        ok "Checksum verified"
    else
        err "Checksum mismatch!
    Expected: $EXPECTED
    Actual:   $ACTUAL

    The image may be corrupted. Please re-download."
    fi
fi

# ── Flash eMMC ──────────────────────────────────────────────────────

log "Starting flash to $EMMC_DEVICE..."
echo ""
echo -e "${BOLD}Flashing... This will take 3-5 minutes. Do not power off!${NC}"
echo ""

# Sync before flash
sync

# Detect if image is gzipped
if [[ "$IMAGE_PATH" == *.gz ]]; then
    # Decompress and write with progress
    if command -v pv &>/dev/null; then
        # Use pv for nice progress bar
        pv -pterb "$IMAGE_PATH" | gunzip -c | dd of="$EMMC_DEVICE" bs=4M conv=fsync status=none
    else
        # Fallback to dd progress
        gunzip -c "$IMAGE_PATH" | dd of="$EMMC_DEVICE" bs=4M conv=fsync status=progress
    fi
elif [[ "$IMAGE_PATH" == *.xz ]]; then
    # images de la release (#3233) : .img.xz
    if command -v pv &>/dev/null; then
        pv -pterb "$IMAGE_PATH" | xz -dc | dd of="$EMMC_DEVICE" bs=4M conv=fsync status=none
    else
        xz -dc "$IMAGE_PATH" | dd of="$EMMC_DEVICE" bs=4M conv=fsync status=progress
    fi
else
    # Raw image
    if command -v pv &>/dev/null; then
        pv -pterb "$IMAGE_PATH" | dd of="$EMMC_DEVICE" bs=4M conv=fsync status=none
    else
        dd if="$IMAGE_PATH" of="$EMMC_DEVICE" bs=4M conv=fsync status=progress
    fi
fi

# Final sync
sync
log "Sync complete"

# ── Verify write ────────────────────────────────────────────────────

log "Verifying flash..."

# Re-read partition table
partprobe "$EMMC_DEVICE" 2>/dev/null || true
sleep 1

# Check if partitions are present
if lsblk "$EMMC_DEVICE" | grep -q "part"; then
    ok "Partitions detected on eMMC"
else
    warn "No partitions detected - may need manual check"
fi

# ── Success ─────────────────────────────────────────────────────────

echo ""
echo -e "${GREEN}${BOLD}╔═══════════════════════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}${BOLD}║              Flash Complete!                                   ║${NC}"
echo -e "${GREEN}${BOLD}╚═══════════════════════════════════════════════════════════════╝${NC}"
echo ""
echo "SecuBox has been flashed to the eMMC."
echo ""
echo "Next steps:"
echo "  1. Remove the USB drive"
echo "  2. Power cycle the board"
echo "  3. The board will boot SecuBox from eMMC"
echo ""

# ── Reboot ──────────────────────────────────────────────────────────

if [[ $NO_REBOOT -eq 1 ]]; then
    log "No-reboot flag set - staying in live system"
    echo "Run 'reboot' when ready to boot from eMMC."
elif [[ $AUTO_MODE -eq 1 ]]; then
    log "Auto mode - rebooting in 10 seconds..."
    echo "Rebooting in 10 seconds (remove USB drive)..."
    sleep 10
    reboot
else
    echo ""
    read -p "Remove USB drive and press Enter to reboot, or Ctrl+C to stay: "
    log "User initiated reboot"
    reboot
fi
