#!/usr/bin/env bash
set -Eeuo pipefail

# setup-rpi.sh
# Interactive Raspberry Pi setup helper for MyETrade / TCS / DMS devices.
# Run:
#   chmod +x setup-rpi.sh
#   ./setup-rpi.sh
# Or:
#   curl -fsSL <url>/setup-rpi.sh | bash

APP_NAME="setup-rpi"
GO_VERSION="${GO_VERSION:-1.25.0}"
NODE_VERSION="${NODE_VERSION:-22}"
PORTAINER_PORT="${PORTAINER_PORT:-9000}"
MARIADB_VERSION="${MARIADB_VERSION:-11.8.8}"

need_sudo() {
  if [ "${EUID:-$(id -u)}" -ne 0 ]; then
    sudo "$@"
  else
    "$@"
  fi
}

pause() {
  read -r -p "Press Enter to continue..." _
}

exists() {
  command -v "$1" >/dev/null 2>&1
}

header() {
  clear || true
  echo "============================================================"
  echo " $1"
  echo "============================================================"
}

detect_desktop_env() {
  # Check running compositors (most reliable when run inside the GUI session)
  if pgrep -x wayfire >/dev/null 2>&1 || pgrep -x labwc >/dev/null 2>&1; then
    echo "wayland"
    return
  fi
  if pgrep -x lxpanel >/dev/null 2>&1 || pgrep -x openbox >/dev/null 2>&1 || pgrep -x mutter >/dev/null 2>&1; then
    echo "lxde"
    return
  fi

  # Check XDG session type
  case "${XDG_SESSION_TYPE:-}" in
    wayland) echo "wayland"; return ;;
    x11)     echo "lxde"; return ;;
  esac

  # Check XDG_CURRENT_DESKTOP
  case "${XDG_CURRENT_DESKTOP:-}" in
    LXDE*|LXDE-pi*|XFCE*|MATE*) echo "lxde"; return ;;
    *wayfire*|*labwc*|*wlroots*|sway*) echo "wayland"; return ;;
  esac

  # Fall back to OS codename
  if [ -f /etc/os-release ]; then
    . /etc/os-release
    case "${VERSION_CODENAME:-}" in
      bookworm|trixie) echo "wayland" ;;
      bullseye|buster) echo "lxde" ;;
      *)               echo "" ;;
    esac
  fi
}

is_gui_available() {
  [ -n "${DISPLAY:-}" ] || [ -n "${WAYLAND_DISPLAY:-}" ] && return 0
  [ "$(systemctl get-default 2>/dev/null)" != "multi-user.target" ] && return 0
  return 1
}

set_ini_key() {
  local file="$1" key="$2" value="$3"
  mkdir -p "$(dirname "$file")"
  if [ -f "$file" ] && grep -q "^${key}=" "$file" 2>/dev/null; then
    sed -i "s|^${key}=.*|${key}=${value}|" "$file"
  else
    echo "${key}=${value}" >> "$file"
  fi
}

set_section_key() {
  local file="$1" section="$2" key="$3" value="$4"
  mkdir -p "$(dirname "$file")"
  [ ! -f "$file" ] && touch "$file"
  if grep -q "^\[${section}\]" "$file"; then
    if sed -n "/^\[${section}\]/,/^\[/p" "$file" | grep -q "^${key}[[:space:]]*="; then
      sed -i "/^\[${section}\]/,/^\[/ s|^${key}[[:space:]]*=.*|${key} = ${value}|" "$file"
    else
      sed -i "/^\[${section}\]/a ${key} = ${value}" "$file"
    fi
  else
    printf '\n[%s]\n%s = %s\n' "$section" "$key" "$value" >> "$file"
  fi
}

set_pcmanfm_desktop_item() {
  local file="$1" item="$2" icon_path="$3" visible="$4"
  mkdir -p "$(dirname "$file")"
  if [ ! -f "$file" ]; then
    cat > "$file" <<EOF
[*]
wallpaper_mode=stretch
wallpaper_common=1
EOF
  fi
  if grep -q "^\[${item}\]" "$file"; then
    sed -i "/^\[${item}\]/,/^\[/ s|^show=.*|show=${visible}|" "$file"
  else
    printf '\n[%s]\ntype=place\npath=%s\nshow=%s\n' "$item" "$icon_path" "$visible" >> "$file"
  fi
}

get_os() {
  if [ -f /etc/os-release ]; then
    . /etc/os-release
    echo "${PRETTY_NAME:-Unknown}"
  else
    uname -a
  fi
}

get_model() {
  tr -d '\0' < /proc/device-tree/model 2>/dev/null || echo "Unknown"
}

status_cmd() {
  local cmd="$1"
  local label="$2"
  if exists "$cmd"; then
    echo "$label: $($cmd --version 2>/dev/null | head -n1 || command -v "$cmd")"
  else
    echo "$label: N/A"
  fi
}

tailscale_status() {
  if ! exists tailscale; then
    echo "Tailscale: N/A"
    return
  fi
  if tailscale status >/dev/null 2>&1; then
    echo "Tailscale: Connected"
  else
    echo "Tailscale: Installed, not connected"
  fi
}

hermes_status() {
  if ! exists hermes; then
    echo "Hermes: N/A"
    return
  fi
  local ver
  ver="$(hermes --version 2>/dev/null || true)"
  echo "Hermes: ${ver:-installed}"

  if exists hermes-gateway; then
    if pgrep -x hermes-gateway >/dev/null 2>&1; then
      echo "Hermes Gateway: running"
    else
      echo "Hermes Gateway: installed (not running)"
    fi
  else
    echo "Hermes Gateway: N/A"
  fi
}

opencode_status() {
  if ! exists opencode; then
    echo "Opencode: N/A"
    return
  fi
  local ver
  ver="$(opencode --version 2>/dev/null || true)"
  echo "Opencode: ${ver:-installed}"
}

mariadb_status() {
  if ! exists mariadb; then
    echo "MariaDB: N/A"
    return
  fi
  local ver
  ver="$(mariadb --version 2>/dev/null || true)"
  local svc
  svc="$(systemctl is-active mariadb 2>/dev/null || echo 'unknown')"
  if [ "$svc" = "active" ]; then
    echo "MariaDB: ${ver} / running"
  else
    echo "MariaDB: ${ver} (${svc})"
  fi
}

docker_status() {
  if ! exists docker; then
    echo "Docker: N/A"
    return
  fi
  local ver
  ver="$(docker --version 2>/dev/null || true)"
  if docker ps >/dev/null 2>&1; then
    echo "Docker: ${ver} / usable"
  else
    echo "Docker: ${ver} / permission issue or service not running"
  fi
}

show_system_info() {
  header "Raspberry Pi Setup"
  echo "User:        $(whoami)"
  echo "Hostname:    $(hostname)"
  echo "Model:       $(get_model)"
  echo "OS:          $(get_os)"
  echo "Kernel:      $(uname -r)"
  local net_ssid
  net_ssid=$(nmcli -t -f active,ssid dev wifi 2>/dev/null | grep '^yes' | cut -d: -f2)
  echo "Network:     ${net_ssid:-N/A}"
  if iw dev wlan0 info 2>/dev/null | grep -q 'type AP'; then
    local hotspot_ssid
    hotspot_ssid=$(iw dev wlan0 info 2>/dev/null | awk '/ssid/ {print $2}')
    echo "Hotspot:     ${hotspot_ssid:-enabled}"
  fi
  echo
}

show_program_status() {
  status_cmd node "Node"
  status_cmd npm "npm"
  status_cmd pm2 "PM2"
  status_cmd go "Go"
  tailscale_status
  hermes_status
  opencode_status
  status_cmd rustdesk "RustDesk"
  docker_status
  if docker ps --format '{{.Names}}' 2>/dev/null | grep -qx portainer; then
    echo "Portainer: Running on :${PORTAINER_PORT}"
  else
    echo "Portainer: N/A"
  fi
  mariadb_status
  echo
}

check_status() {
  show_system_info
  echo "Checking program versions..."
  echo
  show_program_status
  pause
}

install_apt_base() {
  header "APT update and base packages"
  need_sudo apt-get update
  need_sudo apt-get install -y \
    curl wget git ca-certificates gnupg lsb-release unzip tar jq \
    build-essential net-tools dnsutils htop vim
  pause
}

configure_raspi() {
  header "Raspberry Pi config"
  if exists raspi-config; then
    echo "Enabling SSH..."
    need_sudo raspi-config nonint do_ssh 0 || true

    echo "Enabling serial hardware, disabling serial console..."
    need_sudo raspi-config nonint do_serial_hw 0 || true
    need_sudo raspi-config nonint do_serial_cons 1 || true

    echo "Disabling splash screen..."
    need_sudo raspi-config nonint do_boot_splash 1 || true
  else
    echo "raspi-config not found. Skipped."
  fi

  echo "Ensuring SSH service is enabled..."
  need_sudo systemctl enable --now ssh || true
  pause
}

set_hotspot() {
  header "Wi-Fi Hotspot"
  read -r -p "SSID [$(hostname)]: " ssid
  if [ "$ssid" = $'\033' ]; then
    echo "Cancelled."
    pause
    return
  fi
  ssid="${ssid:-$(hostname)}"
  read -r -p "Password [0122799846]: " password
  password="${password:-0122799846}"
  read -r -p "Interface [wlan0]: " ifname
  ifname="${ifname:-wlan0}"
  echo "Creating hotspot: ${ssid} on ${ifname}..."
  need_sudo nmcli device wifi hotspot ssid "$ssid" password "$password" ifname "$ifname"
  pause
}

set_hostname() {
  header "Set Hostname"
  read -r -p "New hostname, blank to cancel: " new_host
  [ -z "$new_host" ] && return
  need_sudo hostnamectl set-hostname "$new_host"
  echo "Hostname set to $new_host. Reboot recommended."
  pause
}

set_static_ip() {
  header "Static IP"
  echo "This uses NetworkManager nmcli when available."
  read -r -p "Interface, e.g. eth0/wlan0: " iface
  read -r -p "IP/CIDR, e.g. 192.168.1.50/24: " ipaddr
  read -r -p "Gateway, e.g. 192.168.1.1: " gateway
  read -r -p "DNS, e.g. 1.1.1.1,8.8.8.8: " dns
  [ -z "$iface" ] || [ -z "$ipaddr" ] || [ -z "$gateway" ] && echo "Missing input. Skipped." && pause && return

  if exists nmcli; then
    local con
    con="$(nmcli -t -f NAME,DEVICE con show --active | awk -F: -v dev="$iface" '$2==dev{print $1; exit}')"
    if [ -z "$con" ]; then
      con="$iface"
    fi
    need_sudo nmcli con mod "$con" ipv4.addresses "$ipaddr" ipv4.gateway "$gateway" ipv4.method manual
    [ -n "$dns" ] && need_sudo nmcli con mod "$con" ipv4.dns "$dns"
    need_sudo nmcli con down "$con" || true
    need_sudo nmcli con up "$con" || true
  else
    echo "nmcli not found. Please configure static IP manually for this OS."
  fi
  pause
}

install_tailscale() {
  header "Install Tailscale"
  if exists tailscale; then
    echo "Tailscale already installed."
  else
    curl -fsSL https://tailscale.com/install.sh | sh
  fi
  pause
}

connect_tailscale() {
  header "Connect Tailscale"
  if ! exists tailscale; then
    echo "Tailscale not installed. Install it first."
    pause
    return
  fi

  if tailscale status >/dev/null 2>&1; then
    echo "Tailscale already connected."
    tailscale status | head -n 20
    pause
    return
  fi

  read -r -p "Paste auth key, blank for browser login: " auth_key
  if [ -n "$auth_key" ]; then
    need_sudo tailscale up --auth-key="$auth_key"
  else
    need_sudo tailscale up
  fi
  pause
}

install_node_pm2() {
  header "Install NVM / Node / PM2"
  export NVM_DIR="$HOME/.nvm"
  if [ ! -s "$NVM_DIR/nvm.sh" ]; then
    curl -fsSL https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.1/install.sh | bash
  fi
  # shellcheck disable=SC1091
  . "$NVM_DIR/nvm.sh"
  nvm install "$NODE_VERSION"
  nvm alias default "$NODE_VERSION"
  npm install -g pm2
  echo "Node: $(node -v)"
  echo "npm:  $(npm -v)"
  echo "PM2:  $(pm2 -v)"
  pause
}

install_hermes() {
  header "Install Hermes"
  if exists hermes; then
    echo "Hermes already installed."
    hermes --version 2>/dev/null || true
    if exists hermes-gateway; then
      if pgrep -x hermes-gateway >/dev/null 2>&1; then
        echo "Hermes Gateway: running"
      else
        echo "Hermes Gateway: installed (not running)"
      fi
    fi
    pause
    return
  fi
  curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash
  if exists hermes; then
    echo "Hermes installed successfully."
    hermes --version 2>/dev/null || true
  fi
  pause
}

install_opencode() {
  header "Install Opencode"
  if exists opencode; then
    echo "Opencode already installed."
    opencode --version 2>/dev/null || true
    pause
    return
  fi
  need_sudo npm install -g opencode-ai
  if exists opencode; then
    echo "Opencode installed successfully."
    opencode --version 2>/dev/null || true
  fi
  pause
}

install_go() {
  header "Install Go ${GO_VERSION}"
  local arch tarball url tmp
  arch="$(uname -m)"
  case "$arch" in
    aarch64|arm64) tarball="go${GO_VERSION}.linux-arm64.tar.gz" ;;
    armv7l|armhf)  tarball="go${GO_VERSION}.linux-armv6l.tar.gz" ;;
    x86_64|amd64)  tarball="go${GO_VERSION}.linux-amd64.tar.gz" ;;
    *) echo "Unsupported architecture: $arch"; pause; return ;;
  esac

  url="https://go.dev/dl/${tarball}"
  tmp="/tmp/${tarball}"
  wget -O "$tmp" "$url"
  need_sudo rm -rf /usr/local/go
  need_sudo tar -C /usr/local -xzf "$tmp"

  if ! grep -q '/usr/local/go/bin' "$HOME/.profile" 2>/dev/null; then
    echo 'export PATH=$PATH:/usr/local/go/bin:$HOME/go/bin' >> "$HOME/.profile"
  fi

  export PATH="$PATH:/usr/local/go/bin:$HOME/go/bin"
  go version
  pause
}

install_rustdesk() {
  header "Install RustDesk"
  local arch deb_suffix tmp url
  arch="$(uname -m)"
  case "$arch" in
    aarch64|arm64) deb_suffix="aarch64.deb" ;;
    armv7l|armhf)  deb_suffix="armv7.deb" ;;
    x86_64|amd64)  deb_suffix="x86_64.deb" ;;
    *) echo "Unsupported architecture: $arch"; pause; return ;;
  esac

  url=$(wget -qO- "https://api.github.com/repos/rustdesk/rustdesk/releases/latest" | \
        sed -n 's/.*"browser_download_url": *"\([^"]*'"${deb_suffix}"'\)".*/\1/p') || true
  if [ -z "$url" ]; then
    echo "Could not find RustDesk ${deb_suffix} in the latest release."
    pause
    return
  fi

  tmp="/tmp/$(basename "$url")"
  echo "Downloading $url"
  if ! wget -O "$tmp" "$url"; then
    echo "Download failed."
    pause
    return
  fi

  need_sudo apt-get install -y "$tmp" || need_sudo apt-get -f install -y
  pause
}

install_docker() {
  header "Install Docker"
  if exists docker; then
    echo "Docker already installed."
  else
    curl -fsSL https://get.docker.com | sh
  fi

  need_sudo systemctl enable --now docker || true
  need_sudo usermod -aG docker "$USER" || true

  echo
  echo "Added $USER to docker group."
  echo "Log out/in or reboot before running Docker without sudo."
  pause
}

install_portainer() {
  header "Install Portainer"
  if ! exists docker; then
    echo "Docker not installed. Install Docker first."
    pause
    return
  fi

  local docker_cmd="docker"
  if ! docker ps >/dev/null 2>&1; then
    docker_cmd="sudo docker"
  fi

  $docker_cmd volume create portainer_data || true
  if $docker_cmd ps -a --format '{{.Names}}' | grep -qx portainer; then
    echo "Portainer container already exists. Starting..."
    $docker_cmd start portainer || true
  else
    $docker_cmd run -d \
      -p "${PORTAINER_PORT}:9000" \
      --name portainer \
      --restart=always \
      -v /var/run/docker.sock:/var/run/docker.sock \
      -v portainer_data:/data \
      portainer/portainer-ce:latest
  fi

  echo "Portainer: http://$(hostname -I | awk '{print $1}'):${PORTAINER_PORT}"
  pause
}

install_mariadb() {
  header "Install MariaDB ${MARIADB_VERSION}"

  if exists mariadb; then
    echo "MariaDB already installed."
    mariadb --version 2>/dev/null || true
    pause
    return
  fi

  need_sudo apt-get update
  need_sudo apt-get install -y curl wget apt-transport-https

  curl -fsSL https://downloads.mariadb.com/MariaDB/mariadb_repo_setup \
    | need_sudo bash -s -- --mariadb-server-version="mariadb-${MARIADB_VERSION}"

  need_sudo apt-get update
  need_sudo apt-get install -y mariadb-server

  echo
  echo "MariaDB installed: $(mariadb --version 2>/dev/null || true)"
  echo
  echo "Running mariadb-secure-installation..."
  need_sudo mariadb-secure-installation

  if exists tailscale && tailscale status >/dev/null 2>&1; then
    echo
    echo "Setting up Tailscale funnel for MariaDB (8806 -> localhost:3306)..."
    need_sudo tailscale funnel --bg --tcp 8806 tcp://localhost:3306
  else
    echo
    echo "Tailscale not connected. Skipping funnel setup."
    echo "Run later: sudo tailscale funnel --bg --tcp 8806 tcp://localhost:3306"
  fi
  pause
}

configure_desktop() {
  header "Configure Desktop Environment"

  if ! is_gui_available; then
    echo "No graphical environment detected (headless or SSH session)."
    echo "Skipping desktop configuration."
    pause
    return
  fi

  local de wallpaper changes=() codename
  if [ -f /etc/os-release ]; then
    . /etc/os-release
    codename="${VERSION_CODENAME:-}"
  fi
  de="$(detect_desktop_env)"

  if [ -z "$de" ]; then
    echo "Could not detect a supported Raspberry Pi OS desktop (Bookworm/Wayland or Bullseye/LXDE)."
    echo "OS: $(get_os)"
    echo "Try running this from inside the desktop GUI session."
    echo "Skipping desktop configuration."
    pause
    return
  fi

  echo "Detected desktop environment: ${de} (${codename:-})"
  echo
  echo "Applying desktop settings..."
  echo

  wallpaper="/usr/share/rpd-wallpaper/RPiSystem_dark.png"

  # ---- Dark theme (both DEs) ----
  echo "  - Dark theme: PiXflat-Dark"
  echo "    -> ~/.config/gtk-3.0/settings.ini"
  set_ini_key "$HOME/.config/gtk-3.0/settings.ini" "gtk-theme-name" "PiXflat-Dark"
  echo "    -> ~/.config/gtk-4.0/settings.ini"
  set_ini_key "$HOME/.config/gtk-4.0/settings.ini" "gtk-theme-name" "PiXflat-Dark"
  changes+=("Dark theme (PiXflat-Dark)")

  if [ "$de" = "lxde" ]; then
    local lxses="$HOME/.config/lxsession/LXDE-pi/desktop.conf"
    echo "    -> ${lxses}"
    set_ini_key "$lxses" "sGtk/ThemeName" "PiXflat-Dark"
  fi

  # ---- Cursor size 48px ----
  echo "  - Cursor size: 48px"
  echo "    -> ~/.config/gtk-3.0/settings.ini"
  set_ini_key "$HOME/.config/gtk-3.0/settings.ini" "gtk-cursor-theme-size" "48"
  changes+=("Cursor size (48px)")

  if [ "$de" = "wayland" ]; then
    if [ -f "$HOME/.config/wayfire.ini" ]; then
      echo "    -> ~/.config/wayfire.ini [input] xcursor_size"
      set_section_key "$HOME/.config/wayfire.ini" "input" "xcursor_size" "48"
    fi
  else
    local xres="$HOME/.Xresources"
    echo "    -> ${xres}"
    mkdir -p "$(dirname "$xres")"
    if [ -f "$xres" ] && grep -q "^Xcursor.size:" "$xres" 2>/dev/null; then
      sed -i "s/^Xcursor.size:.*/Xcursor.size: 48/" "$xres"
    else
      echo "Xcursor.size: 48" >> "$xres"
    fi
  fi

  # ---- Panel position ----
  echo "  - Panel position: bottom"
  if [ "$de" = "wayland" ]; then
    if [ -f "$HOME/.config/wf-panel-pi.ini" ]; then
      echo "    -> ~/.config/wf-panel-pi.ini"
      set_section_key "$HOME/.config/wf-panel-pi.ini" "panel" "position" "bottom"
      changes+=("Panel moved to bottom")
    else
      echo "    Skipped: wf-panel-pi.ini not found (panel may use waybar or sfwbar)"
    fi
  else
    local panel="$HOME/.config/lxpanel/LXDE-pi/panels/panel"
    echo "    -> ${panel}"
    mkdir -p "$(dirname "$panel")"
    if [ -f "$panel" ] && grep -q "^edge=" "$panel" 2>/dev/null; then
      sed -i "s/^edge=.*/edge=bottom/" "$panel"
    elif [ -f "$panel" ] && grep -q "^Global" "$panel" 2>/dev/null; then
      sed -i "/^Global/a edge=bottom" "$panel"
    else
      printf 'Global {\n  edge=bottom\n}\n' > "$panel"
    fi
    changes+=("Panel moved to bottom")
  fi

  # ---- Wallpaper ----
  echo "  - Wallpaper: RPiSystem_dark.png"
  if [ -f "$wallpaper" ]; then
    local pcman="$HOME/.config/pcmanfm/LXDE-pi/desktop-items-0.conf"
    echo "    -> ${pcman}"
    mkdir -p "$(dirname "$pcman")"
    # Ensure [*] section exists and wallpaper is set within it
    if [ ! -f "$pcman" ]; then
      printf '[*]\nwallpaper_mode=stretch\nwallpaper=%s\n' "$wallpaper" > "$pcman"
    elif grep -q "^wallpaper=" "$pcman" 2>/dev/null; then
      sed -i "s|^wallpaper=.*|wallpaper=${wallpaper}|" "$pcman"
    else
      sed -i "1i wallpaper=${wallpaper}" "$pcman"
    fi
    changes+=("Wallpaper (RPiSystem_dark.png)")
  else
    echo "    Warning: ${wallpaper} not found. Wallpaper not changed."
  fi

  # ---- Desktop icons: hide Home and Wastebasket ----
  echo "  - Hide desktop icons: Home folder, Wastebasket"
  local pcman="$HOME/.config/pcmanfm/LXDE-pi/desktop-items-0.conf"
  echo "    -> ${pcman} [Trash] show=0"
  set_pcmanfm_desktop_item "$pcman" "Trash" "trash:///" "0"
  echo "    -> ${pcman} [Home] show=0"
  set_pcmanfm_desktop_item "$pcman" "Home" "$HOME" "0"
  changes+=("Home folder hidden")
  changes+=("Wastebasket hidden")

  # ---- Summary ----
  echo
  echo "Desktop configuration complete:"
  local c
  for c in "${changes[@]}"; do
    echo "  - ${c}"
  done
  echo
  echo "A logout or reboot is recommended for all changes to take effect."
  pause
}

setup_chrome() {
  header "Setup Google Chrome"
  local URL="http://localhost:8080"
  local POLICY_DIR="/etc/chromium/policies/managed"
  local POLICY_FILE="$POLICY_DIR/kiosk-settings.json"

  need_sudo mkdir -p "$POLICY_DIR"

  need_sudo tee "$POLICY_FILE" >/dev/null <<EOF
{
  "RestoreOnStartup": 4,
  "RestoreOnStartupURLs": ["$URL"],
  "AutofillAddressEnabled": false,
  "AutofillCreditCardEnabled": false,
  "SpellcheckEnabled": false,
  "ShowHomeButton": false,
  "BookmarkBarEnabled": false
}
EOF

  echo "Chromium policies written to: $POLICY_FILE"

  gsettings set org.gnome.desktop.interface color-scheme 'prefer-dark' 2>/dev/null || true
  gsettings set org.gnome.desktop.interface gtk-theme 'Adwaita-dark' 2>/dev/null || true

  xdg-settings set default-web-browser chromium-browser.desktop 2>/dev/null || \
  xdg-settings set default-web-browser chromium.desktop 2>/dev/null || true

  pause
}

main_menu() {
  exec </dev/tty
  while true; do
    show_system_info
    cat <<MENU
Options:
   1) Check status
   2) APT update + base packages
   3) raspi-config: SSH / serial / splash
   4) Configure desktop environment
    5) Set Hotspot
    6) Set Hostname
    7) Set Static IP
    8) Install Tailscale
    9) Connect Tailscale
   10) Install NVM / Node / npm / PM2
   11) Install Go
   12) Install Hermes
   13) Install Opencode
   14) Install RustDesk
   15) Install Docker
   16) Install Portainer
   17) Install MariaDB
   18) Setup Google Chrome
   19) Reboot
    0) Exit

MENU
    read -r -p "Enter numbers, comma separated: " input
    [ -z "$input" ] && continue

    IFS=',' read -ra choices <<< "$input"
    for raw in "${choices[@]}"; do
      opt="$(echo "$raw" | xargs)"
      case "$opt" in
        1) check_status ;;
        2) install_apt_base ;;
        3) configure_raspi ;;
        4) configure_desktop ;;
        5) set_hotspot ;;
        6) set_hostname ;;
        7) set_static_ip ;;
        8) install_tailscale ;;
        9) connect_tailscale ;;
        10) install_node_pm2 ;;
        11) install_go ;;
        12) install_hermes ;;
        13) install_opencode ;;
        14) install_rustdesk ;;
        15) install_docker ;;
        16) install_portainer ;;
        17) install_mariadb ;;
        18) setup_chrome ;;
        19) need_sudo reboot ;;
        0) exit 0 ;;
        *) echo "Unknown option: $opt"; sleep 1 ;;
      esac
    done
  done
}

main_menu
