#!/usr/bin/env bash
# shellcheck shell=bash
#
# Phoebus OS installer entry point.
#
# Usage:
#   ai-installer                 start the text UI
#   ai-installer --dry-run       start the UI with no disk changes
#   ai-installer --config FILE   load a saved configuration
#   ai-installer --plan          print the installation plan and exit
#   ai-installer --install       run the deterministic backend (no TUI)
#   ai-installer --yes           skip interactive confirmations (unattended)
#   ai-installer --luks-passphrase-file FILE
#   ai-installer --user-password-file FILE
#   ai-installer --root-password-file FILE
#   ai-installer --bootstrap-opencode
#
# The deterministic backend can be used without the TUI. The TUI is only a
# front-end over the same configuration state and backend functions.
# Secret files must be mode 0600; their contents are never logged.

PHOEBUS_VERSION="0.1.0"

set -uo pipefail

# Locate the project root (the directory containing lib/, tui/, config/).
_self="${BASH_SOURCE[0]}"
while [[ -L "$_self" ]]; do
  _self="$(readlink "$_self")"
done
PHOEBUS_ROOT="$(cd "$(dirname "$_self")/.." && pwd)"
export PHOEBUS_ROOT

CONFIG_FILE=""
MODE="tui"
UI_BACKEND="${UI_BACKEND:-auto}"
STATE_DIR="${STATE_DIR:-/run/ai-installer}"
LUKS_PW_FILE=""
USER_PW_FILE=""
ROOT_PW_FILE=""

# read_secret_file FILE - read a secret without echoing it; returns non-zero
# when the file is missing or unreadable. The value is never logged.
read_secret_file() {
  local file="$1"
  [[ -r "$file" ]] || { printf 'cannot read secret file: %s\n' "$file" >&2; return 1; }
  local value
  value="$(cat -- "$file")"
  printf '%s' "${value%$'\n'}"
}

# --- argument parsing -------------------------------------------------------
while (($#)); do
  case "$1" in
    --dry-run)  CLI_DRY_RUN=yes ;;
    --yes|-y)   CLI_ASSUME_YES=yes ;;
    --config)   shift; CONFIG_FILE="${1:-}" ;;
    --plan)     MODE="plan" ;;
    --install)  MODE="install" ;;
    --backend)  MODE="plan" ;;
    --ui)       shift; UI_BACKEND="${1:-}" ;;
    --luks-passphrase-file) shift; LUKS_PW_FILE="${1:-}" ;;
    --user-password-file)   shift; USER_PW_FILE="${1:-}" ;;
    --root-password-file)   shift; ROOT_PW_FILE="${1:-}" ;;
    --bootstrap-opencode) MODE="opencode" ;;
    --version|-V) printf '%s %s\n' "Phoebus installer" "$PHOEBUS_VERSION"; exit 0 ;;
    --help|-h)
      sed -n '3,20p' "$_self" | sed 's/^# \{0,1\}//'
      exit 0 ;;
    *) printf 'Unknown option: %s\n' "$1" >&2; exit 2 ;;
  esac
  shift
done

export UI_BACKEND

# --- load libraries ---------------------------------------------------------
# shellcheck source=/dev/null
for lib in state logging confirm hardware disks validation plan pkgpolicy \
           portage partitions filesystem encryption btrfs network kernel boot \
           users desktop opencode ai install; do
  source "$PHOEBUS_ROOT/lib/$lib.sh"
done
# shellcheck source=/dev/null
for tui in ui screens menu; do
  source "$PHOEBUS_ROOT/tui/$tui.sh"
done

# --- initialize state -------------------------------------------------------
mkdir -p "$STATE_DIR" 2>/dev/null || STATE_DIR="/tmp/ai-installer"
export STATE_DIR

config_load_defaults "$PHOEBUS_ROOT/config/defaults.conf"
[[ -n "$CONFIG_FILE" ]] && config_load_file "$CONFIG_FILE"

[[ -n "${CLI_DRY_RUN:-}" ]] && config_set DRY_RUN "$CLI_DRY_RUN"
[[ -n "${CLI_ASSUME_YES:-}" ]] && config_set ASSUME_YES "$CLI_ASSUME_YES"

log_init

# --- load secrets from files (unattended installs only) ---------------------
if [[ -n "$LUKS_PW_FILE" ]]; then
  LUKS_PASSPHRASE="$(read_secret_file "$LUKS_PW_FILE")" || exit 1
  secret_register "$LUKS_PASSPHRASE"
fi
if [[ -n "$USER_PW_FILE" ]]; then
  USER_PASSWORD="$(read_secret_file "$USER_PW_FILE")" || exit 1
  secret_register "$USER_PASSWORD"
fi
if [[ -n "$ROOT_PW_FILE" ]]; then
  ROOT_PASSWORD="$(read_secret_file "$ROOT_PW_FILE")" || exit 1
  secret_register "$ROOT_PASSWORD"
fi

# --- run --------------------------------------------------------------------
case "$MODE" in
  plan)
    plan_generate
    plan_render
    printf '\n'
    printf 'Validation:\n'
    problems="$(validate_config)"
    if [[ -z "$problems" ]]; then printf '  OK\n'; else printf '%s\n' "$problems" | sed 's/^/  - /'; fi
    exit 0
    ;;
  install)
    plan_generate
    if [[ -n "$(validate_config)" ]]; then
      log_error "configuration is incomplete; run --plan to inspect"
      exit 1
    fi
    if ! confirm_erase "$(plan_destructive_preview)"; then
      log_error "installation not confirmed"
      exit 1
    fi
    destructive_grant
    rc=0
    install_run || rc=$?
    destructive_revoke
    exit "$rc"
    ;;
  opencode)
    if opencode_ensure; then
      printf 'OpenCode ready at %s\n' "$(opencode_detect)"
      exit 0
    fi
    exit 1
    ;;
  tui)
    if ! ui_init; then
      printf 'No dialog/whiptail found. Use --plan or --install for the backend.\n' >&2
      exit 1
    fi
    menu_main
    exit 0
    ;;
esac
