#!/usr/bin/env bash
# ============================================================================
#  CachyOS Toolkit – Postinstall & Wartung für CachyOS (AMD/Intel-CPU, NVIDIA/AMD-GPU)
#  https://ts.lutti-multigaming.de/guides/cachyos-toolkit.html
#
#  Aufruf:   ./cachyos-toolkit.sh              interaktives Menü
#            ./cachyos-toolkit.sh --list       alle Aktionen auflisten
#            ./cachyos-toolkit.sh <aktion> …   Aktionen direkt ausführen (z. B. sys_update game_base)
#            ./cachyos-toolkit.sh --quick      empfohlener Schnellstart für ein frisches System
#  Optionen: DRYRUN=1 (nur anzeigen), ASSUME_YES=1 (keine Rückfragen), NO_COLOR=1
#  Als normaler Benutzer starten – sudo wird bei Bedarf abgefragt.
# ============================================================================
# kein pipefail: grep -q in Pipes (lsmod | grep -q …) würde sonst per SIGPIPE fehlschlagen

TOOLKIT_DIR="$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")" && pwd)"
export TOOLKIT_DIR
source "$TOOLKIT_DIR/lib/common.sh"

# ---------- Module laden ----------
declare -a MOD_FILES=() MOD_TITLES=() MOD_DESCS=()
declare -A MOD_ACTIONS=()      # modulindex -> "func|desc\nfunc|desc…"
declare -A ACTION_DESC=()      # func -> desc
declare -a ALL_ACTIONS=()

load_modules() {
  local f i=0
  for f in "$TOOLKIT_DIR"/modules/[0-9]*.sh; do
    ACTIONS=()
    # shellcheck source=/dev/null
    source "$f"
    MOD_FILES+=("$f"); MOD_TITLES+=("$MODULE_TITLE"); MOD_DESCS+=("$MODULE_DESC")
    MOD_ACTIONS[$i]=$(printf '%s\n' "${ACTIONS[@]}")
    local a; for a in "${ACTIONS[@]}"; do ALL_ACTIONS+=("${a%%|*}"); ACTION_DESC["${a%%|*}"]="${a#*|}"; done
    ((i++))
  done
}

# Schnellstart: sinnvolle Reihenfolge für ein frisches System
QUICK=(sys_update sys_base_tools sys_aur_helper sys_trim_smart game_base perf_sysctl_gaming perf_cpu_profile sec_install sec_ufw_basic)

# ---------- Anzeige ----------
banner() {
  clear 2>/dev/null
  printf '%s%s' "$C_BOLD" "$C_AMBER"
  cat <<'B'
   ____           _            ___  ____    _____           _ _    _ _
  / ___|__ _  ___| |__  _   _ / _ \/ ___|  |_   _|__   ___ | | | _(_) |_
 | |   / _` |/ __| '_ \| | | | | | \___ \    | |/ _ \ / _ \| | |/ / | __|
 | |__| (_| | (__| | | | |_| | |_| |___) |   | | (_) | (_) | |   <| | |_
  \____\__,_|\___|_| |_|\__, |\___/|____/    |_|\___/ \___/|_|_|\_\_|\__|
                        |___/
B
  printf '%s' "$C_RESET"
  printf '  %sv%s · %s · Kernel %s · GPU: %s%s\n\n' "$C_DIM" "$TOOLKIT_VERSION" "$(. /etc/os-release; echo "$PRETTY_NAME")" "$(uname -r)" "$(detect_gpu)" "$C_RESET"
}

run_action() {
  local fn="$1"
  declare -F "$fn" >/dev/null || { err "Unbekannte Aktion: $fn"; return 1; }
  _log_file "ACTION $fn"
  "$fn"
  local rc=$?
  (( rc == 0 )) || warn "Aktion $fn endete mit Code $rc"
  return $rc
}

module_menu() {
  local idx="$1" line fns=() descs=()
  while IFS= read -r line; do [[ -n "$line" ]] || continue; fns+=("${line%%|*}"); descs+=("${line#*|}"); done <<< "${MOD_ACTIONS[$idx]}"
  while true; do
    banner
    printf '%s%s%s\n%s%s%s\n\n' "$C_BOLD" "${MOD_TITLES[$idx]}" "$C_RESET" "$C_DIM" "${MOD_DESCS[$idx]}" "$C_RESET"
    local i; for i in "${!fns[@]}"; do printf '  %s%2d%s) %s  %s%s%s\n' "$C_AMBER" $((i+1)) "$C_RESET" "${descs[$i]}" "$C_DIM" "${fns[$i]}" "$C_RESET"; done
    printf '\n  %s a%s) alle Aktionen dieses Moduls nacheinander\n  %s 0%s) zurück\n\n' "$C_AMBER" "$C_RESET" "$C_AMBER" "$C_RESET"
    local sel; read -rp "Auswahl (mehrere mit Leerzeichen): " sel
    [[ "$sel" == 0 || -z "$sel" ]] && return
    if [[ "$sel" == a ]]; then sel=$(seq -s' ' 1 ${#fns[@]}); fi
    local n; for n in $sel; do
      [[ "$n" =~ ^[0-9]+$ && $n -ge 1 && $n -le ${#fns[@]} ]] || { warn "Ungültig: $n"; continue; }
      run_action "${fns[$((n-1))]}"
    done
    pause
  done
}

main_menu() {
  while true; do
    banner
    local i; for i in "${!MOD_TITLES[@]}"; do
      printf '  %s%d%s) %-18s %s%s%s\n' "$C_AMBER" $((i+1)) "$C_RESET" "${MOD_TITLES[$i]}" "$C_DIM" "${MOD_DESCS[$i]}" "$C_RESET"
    done
    printf '\n  %sq%s) Schnellstart für ein frisches System (%s)\n' "$C_AMBER" "$C_RESET" "$(echo "${QUICK[*]}" | sed 's/ /, /g')"
    printf '  %sl%s) Log anzeigen   %sb%s) Backups anzeigen   %s0%s) Beenden\n\n' "$C_AMBER" "$C_RESET" "$C_AMBER" "$C_RESET" "$C_AMBER" "$C_RESET"
    local sel; read -rp "Auswahl: " sel
    case "$sel" in
      0|q_|exit) echo; exit 0 ;;
      q) quick_start; pause ;;
      l) ${PAGER:-less} "$TOOLKIT_LOG" 2>/dev/null || cat "$TOOLKIT_LOG"; ;;
      b) ls -la "$TOOLKIT_BACKUP" 2>/dev/null || info "Noch keine Backups."; pause ;;
      *) [[ "$sel" =~ ^[0-9]+$ && $sel -ge 1 && $sel -le ${#MOD_TITLES[@]} ]] && module_menu $((sel-1)) ;;
    esac
  done
}

quick_start() {
  step "Schnellstart"
  local a; for a in "${QUICK[@]}"; do printf '    • %s\n' "${ACTION_DESC[$a]}"; done
  confirm "Alle ausführen?" y || return
  for a in "${QUICK[@]}"; do run_action "$a"; done
  ok "Schnellstart abgeschlossen – Neustart empfohlen."
}

list_actions() {
  local i line
  for i in "${!MOD_TITLES[@]}"; do
    printf '\n%s%s%s\n' "$C_BOLD" "${MOD_TITLES[$i]}" "$C_RESET"
    while IFS= read -r line; do [[ -n "$line" ]] && printf '  %-22s %s\n' "${line%%|*}" "${line#*|}"; done <<< "${MOD_ACTIONS[$i]}"
  done
}

# ---------- Start ----------
require_not_root
require_cachyos
load_modules

case "${1:-}" in
  -h|--help) sed -n '2,12p' "$0"; exit 0 ;;
  --list)    list_actions; exit 0 ;;
  --quick)   sudo_keepalive; quick_start; exit ;;
  "")        sudo_keepalive; main_menu ;;
  *)         sudo_keepalive; for a in "$@"; do run_action "$a" || exit 1; done ;;
esac
