#!/usr/bin/env bash

INSTALL_DIR="${HOME}/linusware"
RED='\033[0;31m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m'

declare -a editions edition_names
for dir in "${INSTALL_DIR}"/*/; do
  [ -d "$dir" ] || continue
  edition=$(basename "$dir")
  run="${dir}/linusware/run.sh"
  if [ -f "$run" ] && [ -x "$run" ]; then
    edition_names+=("$edition")
    editions+=("$run")
  fi
done

if [ ${#editions[@]} -eq 0 ]; then
  echo -e "${YELLOW}No LinusWare editions installed.${NC}"
  echo "Run the installer first:"
  echo "  curl -fsSL <url> | bash"
  exit 1
fi

get_version() {
  local f="${INSTALL_DIR}/$1/version.txt"
  [ -f "$f" ] && cat "$f" || echo "?"
}

cap() {
  local s="$1"
  echo "$(echo "${s:0:1}" | tr '[:lower:]' '[:upper:]')${s:1}"
}

run_updater() {
  [ -x "${INSTALL_DIR}/update.sh" ] && "${INSTALL_DIR}/update.sh"
  echo ""
  read -rp "Press Enter to return to menu..." _
}

# whiptail TUI
if command -v whiptail >/dev/null 2>&1; then
  while true; do
    menu_items=()
    for i in "${!edition_names[@]}"; do
      v=$(get_version "${edition_names[$i]}")
      menu_items+=("$((i+1))" "$(cap "${edition_names[$i]}") v${v}")
    done
    menu_items+=("u" "Check for Updates")
    menu_items+=("q" "Quit")

    choice=$(whiptail --title "LinusWare Launcher" \
                      --menu "Select an edition to launch:" \
                      15 55 5 "${menu_items[@]}" \
                      3>&1 1>&2 2>&3) || choice="q"

    case "$choice" in
      u) run_updater;;
      q|"") exit 0;;
      *) [[ "$choice" =~ ^[0-9]+$ ]] && exec "${editions[$((choice-1))]}" ;;
    esac
  done
fi

# fallback TUI
while true; do
  echo ""
  echo -e "${CYAN}------ LinusWare Launcher ------${NC}"
  for i in "${!edition_names[@]}"; do
    v=$(get_version "${edition_names[$i]}")
    echo "  $((i+1))) $(cap "${edition_names[$i]}") (v${v})"
  done
  echo "  u) Check for Updates"
  echo "  q) Quit"
  echo ""
  read -rp "Select: " choice

  case "$choice" in
    [qQ]) exit 0;;
    [uU]) run_updater;;
    *)
      if [[ "$choice" =~ ^[0-9]+$ ]] && \
         [ "$choice" -ge 1 ] && \
         [ "$choice" -le "${#editions[@]}" ]; then
        exec "${editions[$((choice-1))]}"
      else
        echo -e "${RED}Invalid choice${NC}"
      fi
      ;;
  esac
done
