#!/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.
#
# common.sh
# Shared helpers for the AM·OS installer suite.

PKGMAIN="amos64"
RELEASE="1.0"

DIALOG_BACKTITLE=" AM·OS Installer $RELEASE "
DIALOG_TTY=""
LIVE_LOG="/tmp/amos-install.log"
TARGET_LOG_REL="/var/log/amos-install.log"

PASSWORD_REVEAL="${PASSWORD_REVEAL:-0}"

TOP_PAD="${TOP_PAD:-1}"
BOT_PAD="${BOT_PAD:-2}"

[ -f "$LIVE_LOG" ] || : > "$LIVE_LOG"

log()  { printf '[%s] %s\n' "$(date '+%H:%M:%S')" "$*" >> "$LIVE_LOG"; }
warn() { log "WARN  $*"; }

open_tty() {
  local t
  for t in /dev/tty /dev/console /dev/tty1 /dev/tty2 /dev/tty3; do
    [ -c "$t" ] || continue
    [ -r "$t" ] && [ -w "$t" ] || continue
    if { exec 9<>"$t"; } 2>/dev/null; then
      DIALOG_TTY="$t"
      write_amos_dialogrc
      write_amos_palette
      return 0
    fi
  done
  return 1
}

close_tty() { exec 9>&- 2>/dev/null || true; DIALOG_TTY=""; }

write_amos_palette() {
    [ -c "${DIALOG_TTY:-}" ] || return 0
    {
        printf '\033]P5%s' "3D1A5B"
        printf '\033]PD%s' "7C3AED"
    } > "$DIALOG_TTY" 2>/dev/null || true
}

write_amos_dialogrc() {
    local rc="${DIALOGRC:-${HOME:-/root}/.dialogrc}"

    cat > "$rc" <<'DIALOGRC_EOF'
use_shadow = OFF
use_colors = ON

screen_color  = (GREEN,BLACK,ON)
shadow_color  = (BLACK,BLACK,OFF)

dialog_color  = (GREEN,BLACK,ON)
title_color   = (YELLOW,BLACK,ON)

border_color  = (YELLOW,BLACK,ON)
border2_color = (YELLOW,BLACK,ON)

button_active_color         = (WHITE,MAGENTA,ON)
button_inactive_color       = (WHITE,MAGENTA,OFF)
button_key_active_color     = (WHITE,MAGENTA,ON)
button_key_inactive_color   = (WHITE,MAGENTA,OFF)
button_label_active_color   = (WHITE,MAGENTA,ON)
button_label_inactive_color = (WHITE,MAGENTA,OFF)

item_color          = (GREEN,BLACK,ON)
item_selected_color = (WHITE,MAGENTA,ON)

tag_color              = (GREEN,BLACK,ON)
tag_selected_color     = (WHITE,MAGENTA,ON)
tag_key_color          = (GREEN,BLACK,ON)
tag_key_selected_color = (WHITE,MAGENTA,ON)

check_color          = (GREEN,BLACK,ON)
check_selected_color = (WHITE,MAGENTA,ON)

uarrow_color = (YELLOW,BLACK,ON)
darrow_color = (YELLOW,BLACK,ON)

inputbox_color          = (GREEN,BLACK,ON)
inputbox_border_color   = (YELLOW,BLACK,ON)
inputbox_border2_color  = (YELLOW,BLACK,ON)
menubox_color           = (GREEN,BLACK,ON)
menubox_border_color    = (YELLOW,BLACK,ON)
menubox_border2_color   = (YELLOW,BLACK,ON)

itemhelp_color           = (GREEN,BLACK,ON)
position_indicator_color = (YELLOW,BLACK,ON)
gauge_color = (MAGENTA,BLACK,ON)
DIALOGRC_EOF

    chmod 644 "$rc"
    export DIALOGRC="$rc"
}

DLG_H=22
DLG_W=80

_pad() {
    local n_top="$TOP_PAD" n_bot="$BOT_PAD"
    local bt="" bb="" i=0
    while [ "$i" -lt "$n_top" ]; do bt="${bt}
"; i=$((i + 1)); done
    i=0
    while [ "$i" -lt "$n_bot" ]; do bb="${bb}
"; i=$((i + 1)); done
    printf '%s\n%s\n%s\n' "$bt" "$1" "$bb" | sed 's/^/  /'
}

dlg_msg() {
    dialog --cr-wrap --no-collapse \
           --title "$1" --msgbox "$(_pad "$2")" "$DLG_H" "$DLG_W" \
           < /dev/tty > /dev/tty
}

dlg_error() {
    dialog --cr-wrap --no-collapse \
           --title "Error" --msgbox "$(_pad "$1")" "$DLG_H" "$DLG_W" \
           < /dev/tty > /dev/tty
}

dlg_info() {
    dialog --cr-wrap --no-collapse \
           --title "$1" --infobox "$2" "$DLG_H" "$DLG_W" \
           < /dev/tty > /dev/tty
}

dlg_yesno() {
    dialog --cr-wrap --no-collapse \
           --title "$1" --yesno "$(_pad "$2")" "$DLG_H" "$DLG_W" \
           < /dev/tty > /dev/tty
}

dlg_password() {
    local title="$1" text="$2"
    if [ "$PASSWORD_REVEAL" = "1" ]; then
        dialog --cr-wrap --no-collapse --stdout \
               --title "$title" --inputbox "$(_pad "$text")" "$DLG_H" "$DLG_W" \
               < /dev/tty
    else
        dialog --cr-wrap --no-collapse --stdout --insecure \
               --title "$title" --passwordbox "$(_pad "$text")" "$DLG_H" "$DLG_W" \
               < /dev/tty
    fi
}

dlg_menu() {
    local title="$1" text="$2"; shift 2
    dialog --cr-wrap --no-collapse --stdout \
           --title "$title" --menu "$text" "$@" \
           < /dev/tty
}

dlg_input() {
    local title="$1" text="$2"; shift 2
    dialog --cr-wrap --no-collapse --stdout \
           --title "$title" --inputbox "$text" "$DLG_H" "$DLG_W" "$@" \
           < /dev/tty
}

dlg_radiolist() {
    local title="$1" text="$2"; shift 2
    dialog --cr-wrap --no-collapse --stdout \
           --title "$title" --radiolist "$text" "$@" \
           < /dev/tty
}

dlg_gauge() {
    dialog --title "$1" --gauge "$2" "$3" "$4"
}

# ---------------------------------------------------------------------------
#  Navigation-aware dialog wrappers.
#
#  These add a third "Back" button (dialog exit code 3). Callers check
#  the exit code:
#
#    yesno:      0 = Yes, 1 = No, 3 = Back, 255 = ESC
#    menu/input: 0 = OK (value on stdout), 1 = Cancel, 3 = Back, 255 = ESC
#
#  Wizard steps treat any of {1,3,255} as "go back" for menu-like
#  dialogs (Cancel and ESC are ambiguous, safer to back out), and
#  treat ESC/Back as "go back" for yesno while respecting Yes/No as
#  real answers. See setup.sh for the walker that interprets these.
# ---------------------------------------------------------------------------

dlg_yesno_nav() {
    dialog --cr-wrap --no-collapse \
           --extra-button --extra-label "Back" \
           --title "$1" --yesno "$(_pad "$2")" "$DLG_H" "$DLG_W" \
           < /dev/tty > /dev/tty
}

dlg_yesno_nav_defaultno() {
    dialog --cr-wrap --no-collapse \
           --extra-button --extra-label "Back" \
           --defaultno \
           --title "$1" --yesno "$(_pad "$2")" "$DLG_H" "$DLG_W" \
           < /dev/tty > /dev/tty
}

dlg_menu_nav() {
    local title="$1" text="$2"; shift 2
    dialog --cr-wrap --no-collapse --stdout \
           --extra-button --extra-label "Back" \
           --title "$title" --menu "$text" "$@" \
           < /dev/tty
}

dlg_radiolist_nav() {
    local title="$1" text="$2"; shift 2
    dialog --cr-wrap --no-collapse --stdout \
           --extra-button --extra-label "Back" \
           --title "$title" --radiolist "$text" "$@" \
           < /dev/tty
}

dlg_input_nav() {
    local title="$1" text="$2"; shift 2
    dialog --cr-wrap --no-collapse --stdout \
           --extra-button --extra-label "Back" \
           --title "$title" --inputbox "$text" "$DLG_H" "$DLG_W" "$@" \
           < /dev/tty
}

dlg_password_nav() {
    local title="$1" text="$2"
    if [ "$PASSWORD_REVEAL" = "1" ]; then
        dialog --cr-wrap --no-collapse --stdout \
               --extra-button --extra-label "Back" \
               --title "$title" --inputbox "$(_pad "$text")" "$DLG_H" "$DLG_W" \
               < /dev/tty
    else
        dialog --cr-wrap --no-collapse --stdout --insecure \
               --extra-button --extra-label "Back" \
               --title "$title" --passwordbox "$(_pad "$text")" "$DLG_H" "$DLG_W" \
               < /dev/tty
    fi
}

part_name() {
  case "$1" in
    *[0-9]) printf '%sp%s\n' "$1" "$2" ;;
    *)      printf '%s%s\n' "$1" "$2" ;;
  esac
}

mkfs_vfat() {
  if command -v mkfs.vfat >/dev/null 2>&1; then
    mkfs.vfat "$@"
  else
    mkfs.fat "$@"
  fi
}

# ---------------------------------------------------------------------------
#  Password prompts.
#
#  Each returns:
#    0  password captured, variable set
#    3  user pressed Back (wizard goes to previous step)
# ---------------------------------------------------------------------------

prompt_root_password() {
  local p1 p2 rc
  while :; do
    p1=$(dlg_password_nav "Root password" \
      "\n  Set password for root account."); rc=$?
    case $rc in
      0) : ;;
      *) return 3 ;;
    esac
    [ -n "$p1" ] || { dlg_error "Password cannot be empty."; continue; }
    [ ${#p1} -ge 6 ] || { dlg_error "Minimum 6 characters."; continue; }

    p2=$(dlg_password_nav "Confirm root password" \
      "\n  Re-enter to confirm."); rc=$?
    case $rc in
      0) : ;;
      *) return 3 ;;
    esac
    [ "$p1" = "$p2" ] || { dlg_error "Passwords do not match."; continue; }

    ROOT_PASSWORD="$p1"
    return 0
  done
}

prompt_user_password() {
  local p1 p2 rc
  while :; do
    p1=$(dlg_password_nav "User password" \
      "\n  Set password for ${USER_NAME:-the user account}."); rc=$?
    case $rc in
      0) : ;;
      *) return 3 ;;
    esac
    [ -n "$p1" ] || { dlg_error "Password cannot be empty."; continue; }
    [ ${#p1} -ge 6 ] || { dlg_error "Minimum 6 characters."; continue; }

    p2=$(dlg_password_nav "Confirm user password" \
      "\n  Re-enter to confirm."); rc=$?
    case $rc in
      0) : ;;
      *) return 3 ;;
    esac
    [ "$p1" = "$p2" ] || { dlg_error "Passwords do not match."; continue; }

    USER_PASSWORD="$p1"
    return 0
  done
}

prompt_luks_passphrase() {
  local p1 p2 rc
  while :; do
    p1=$(dlg_password_nav "Encryption passphrase" \
      "\n  Enter the LUKS passphrase (minimum 8 characters)."); rc=$?
    case $rc in
      0) : ;;
      *) return 3 ;;
    esac
    [ -n "$p1" ] || { dlg_error "Passphrase cannot be empty."; continue; }
    [ ${#p1} -ge 8 ] || { dlg_error "Minimum 8 characters."; continue; }

    p2=$(dlg_password_nav "Confirm passphrase" \
      "\n  Re-enter to confirm."); rc=$?
    case $rc in
      0) : ;;
      *) return 3 ;;
    esac
    [ "$p1" = "$p2" ] || { dlg_error "Passphrases do not match."; continue; }

    LUKS_PASSPHRASE="$p1"
    return 0
  done
}

detect_environment() {
  ENV_TYPE="unknown"
  local product=""
  if command -v dmidecode >/dev/null 2>&1; then
    product=$(dmidecode -s system-product-name 2>/dev/null || true)
  fi
  case "$product" in
    VirtualBox)              ENV_TYPE="virtualbox" ;;
    KVM|QEMU|"Standard PC"*) ENV_TYPE="qemu" ;;
    *)                       ENV_TYPE="physical" ;;
  esac
  if [ "$ENV_TYPE" = "physical" ] && [ -r /sys/class/dmi/id/product_name ]; then
    product=$(cat /sys/class/dmi/id/product_name 2>/dev/null || true)
    case "$product" in
      VirtualBox) ENV_TYPE="virtualbox" ;;
      KVM|QEMU)   ENV_TYPE="qemu" ;;
    esac
  fi

  # ENV_TYPE is informational only. "qemu" covers local slirp VMs AND
  # every KVM-based VPS, so it must not drive any decision. The
  # distinguishing signal is network topology: user-mode NAT always
  # presents gateway 10.0.2.2 with the guest in 10.0.2.0/24. Both
  # conditions together are specific enough that no real LAN matches.
  SLIRP="no"
  local gw ip
  gw=$(ip route show default 2>/dev/null | awk '/default/ {print $3; exit}')
  if [ "$gw" = "10.0.2.2" ]; then
    ip=$(ip -4 addr show 2>/dev/null \
         | awk '/inet 10\.0\.2\./ {print $2; exit}')
    [ -n "$ip" ] && SLIRP="yes"
  fi

  log "Environment: $ENV_TYPE (DMI: ${product:-<none>}) slirp=$SLIRP"
}

# Return 0 if the live environment is using DHCP on $1.
# Signals, strongest first:
#   1. a DHCP client is running
#   2. a DHCP lease file exists
#   3. the address is marked "dynamic"
# (3) is necessary-but-not-sufficient: some clients mark leases
# permanent, so its absence is not proof of static. That is why it
# is checked last.
detect_dhcp() {
  local iface="${1:-}"
  pgrep -af 'udhcpc|dhclient|dhcpcd' >/dev/null 2>&1 && return 0
  ls /var/lib/dhcp*/*.leases /var/lib/dhclient* /run/udhcpc.* \
     /var/lib/dhcpcd/*.lease 2>/dev/null | grep -q . && return 0
  [ -n "$iface" ] && \
    ip -4 addr show dev "$iface" 2>/dev/null | grep -qw dynamic && return 0
  return 1
}

# Returns 0 if $1 is A.B.C.D (mask optional, stripped). Rejects leading
# zeros and out-of-range octets so that arithmetic is never needed.
_valid_ipv4() {
  local ip="${1%%/*}"
  case "$ip" in
    *.*.*.*) ;;
    *) return 1 ;;
  esac
  local IFS=.
  # shellcheck disable=SC2086
  set -- $ip
  [ $# -eq 4 ] || return 1
  local o
  for o in "$@"; do
    case "$o" in
      0|[1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]) ;;
      *) return 1 ;;
    esac
  done
  return 0
}

# Returns 0 if $1 is a plausible default gateway: bare dotted-quad, no
# mask, not in a range that is never a next-hop.
_valid_gateway() {
  case "$1" in */*) return 1 ;; esac
  _valid_ipv4 "$1" || return 1
  local o1="${1%%.*}" rest="${1#*.}"
  case "$o1" in
    0|127) return 1 ;;
    22[4-9]|23[0-9]|24[0-9]|25[0-5]) return 1 ;;
  esac
  case "$o1.${rest%%.*}" in
    169.254) return 1 ;;
  esac
  return 0
}