#!/usr/bin/env bash
set -euo pipefail
INSTALLER_DIR="$HOME/installer"

############################################
# Keyboard layout (live environment)
# To add more layouts: append "code|Display Name" to KEYMAPS
############################################
KEYMAPS=(
    "de-latin1-nodeadkeys|German/Austrian (nodeadkeys)"
    "us|English US"
    "de|German"
)

MODE="${1:-guided}"

if [[ "$MODE" == "auto" ]]; then
    LIVE_KEYMAP="${KEYMAPS[0]%%|*}"
else
    echo "Select keyboard layout:"
    for i in "${!KEYMAPS[@]}"; do
        _km_code="${KEYMAPS[$i]%%|*}"
        _km_name="${KEYMAPS[$i]##*|}"
        printf "  %d) %-32s (%s)\n" $((i+1)) "$_km_name" "$_km_code"
    done
    read -rp "Choice [1]: " _KM_IDX
    _KM_IDX=$(( ${_KM_IDX:-1} - 1 ))
    if (( _KM_IDX >= 0 && _KM_IDX < ${#KEYMAPS[@]} )); then
        LIVE_KEYMAP="${KEYMAPS[$_KM_IDX]%%|*}"
    else
        LIVE_KEYMAP="${KEYMAPS[0]%%|*}"
    fi
fi

loadkeys "$LIVE_KEYMAP"

# ── Action selection (skipped in auto mode) ──────────────────────────────────
if [[ "$MODE" != "auto" ]]; then
    echo ""
    echo "Select action:"
    echo "  1) Install system          (fresh install, erases disk)"
    echo "  2) Reset system            (wipe root, keep user data & passwords)"
    read -rp "Choice [1]: " _ACTION_IDX
    _ACTION_IDX="${_ACTION_IDX:-1}"
    if [[ "$_ACTION_IDX" == "2" ]]; then
        exec bash "$INSTALLER_DIR/reset-arch.sh"
    fi
fi

case "$MODE" in
    auto)   exec bash "$INSTALLER_DIR/arch-autoinstall.sh" "${@:2}" ;;
    guided) exec bash "$INSTALLER_DIR/archbaseos-guided-install.sh" ;;
    *)      exec bash "$INSTALLER_DIR/archbaseos-guided-install.sh" ;;
esac
