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

tty_read() {
  local __var="$1"; shift; local __prompt="$1"; shift || true; local __default="${1:-}"; local __ans=""
  if [ -t 0 ]; then read -r -p "$__prompt" __ans;
  elif [ -e /dev/tty ]; then read -r -p "$__prompt" __ans < /dev/tty; else __ans="$__default"; fi
  if [ -z "$__ans" ] && [ -n "$__default" ]; then __ans="$__default"; fi
  printf -v "$__var" "%s" "$__ans"
}

HOST="scripts.domainmanager.io"
declare -a KEYS NAMES DESCS OSS
KEYS=("install/transfer_to_remote.ps1" "install/windows_script_header_template.ps1" "install/script_header_template.sh" "install/transfer_to_remote.sh" "install/ubuntu_web_stack_setup.sh")
NAMES=("Transfer To Remote" "Windows Script Header Template" "Script Header Template" "Transfer To Remote" "Ubuntu Web Stack Setup")
DESCS=("No description available" "<one-line description> (REPLACE with concise description)" "<one-line description> (REPLACE with concise description)" "Securely transfer file(s)/folder to remote via SSH; auto-compress for multi" "Ubuntu Web Stack Setup: Nginx + PHP-FPM + MySQL + Redis")
OSS=("$ErrorActionPreference = \"Stop\"" "Windows 10+, Windows Server 2019+" "Linux, MacOS, Windows (REPLACE with supported OS list)" "Linux, MacOS 10.15+" "Linux, Ubuntu 20.04+, 22.04+, 24.04+, Debian 11+")

# Detect client OS and filter list
detect_os() {
  case "$(uname -s)" in
    Linux*) echo linux;;
    Darwin*) echo macos;;
    CYGWIN*|MINGW*|MSYS*) echo windows;;
    *) echo unknown;;
  esac
}
CLIENT_OS="$(detect_os)"
VISIBLE=()
for i in "${!KEYS[@]}"; do
  osline="${OSS[i],,}"
  if [ -z "$osline" ]; then VISIBLE+=("$i"); continue; fi
  case "$CLIENT_OS" in
    linux)   echo "$osline" | grep -Eq "linux|ubuntu|debian|centos|rhel|alpine|fedora" && VISIBLE+=("$i");;
    macos)   echo "$osline" | grep -Eq "mac|macos|darwin" && VISIBLE+=("$i");;
    windows) echo "$osline" | grep -Eq "win|windows" && VISIBLE+=("$i");;
    *) VISIBLE+=("$i");;
  esac
done

echo "Available scripts for $CLIENT_OS:"
if [ ${#VISIBLE[@]} -eq 0 ]; then echo "  (none)"; fi
for n in "${!VISIBLE[@]}"; do
  i=${VISIBLE[n]}
  idx=$((n+1))
  printf "  %2d) %s - %s
" "$idx" "${NAMES[i]}" "${DESCS[i]}"
done
echo "  0) Exit"

while true; do
  tty_read CHOICE "Enter number: " "0"
  case "$CHOICE" in
    0|"" ) echo "Bye."; exit 0;;
    *[!0-9]* ) echo "Please enter a number."; continue;;
  esac
  sel=$((CHOICE-1))
  if [ $sel -ge 0 ] && [ $sel -lt ${#VISIBLE[@]} ]; then break; fi
  echo "Invalid selection. Try again."
done

INDEX=${VISIBLE[sel]}
SELECTED_KEY="${KEYS[INDEX]}"
SELECTED_NAME="${NAMES[INDEX]}"
echo "Running: ${SELECTED_NAME}"
echo "----------------------------------------"
curl -fsSL "https://${HOST}/${SELECTED_KEY}" | bash

echo
echo "Done: ${SELECTED_NAME}"