#!/usr/bin/env bash
# ============================================================================
#  Hermes Mission Control — Community Installer  ·  by KomputerMechanic
#  Verifies your membership key, then runs the installer in a temporary folder
#  that is wiped afterwards. The real installer is never stored on your machine.
# ============================================================================
set -euo pipefail
WORKER_URL="https://mission-control-gentle-compass.komputermechanic.com"
TUTORIAL_SLUG="hermes-mission-control"

if [ -t 1 ]; then B=$'\e[1m'; DIM=$'\e[2m'; G=$'\e[38;5;71m'; R=$'\e[38;5;167m'; ACC=$'\e[38;5;208m'; Z=$'\e[0m'
else B=; DIM=; G=; R=; ACC=; Z=; fi

printf '\n  %s%sKomputerMechanic  ~  Hermes Mission Control%s\n' "$B" "$ACC" "$Z"
printf '  %sCommunity installer%s\n\n' "$DIM" "$Z"

command -v curl >/dev/null || { printf '  %scurl is required.%s\n' "$R" "$Z"; exit 1; }

TMP="$(mktemp -d)"; trap 'rm -rf "$TMP"' EXIT

# the "error" from the worker's JSON answer, read properly (a message with a quote in it defeated grep)
_server_reason() {
  python3 -c 'import json, sys
try:
    print((json.load(open(sys.argv[1])).get("error") or "").strip())
except Exception:
    pass' "$1" 2>/dev/null && return 0
  { grep -o '"error":"[^"]*"' "$1" 2>/dev/null || true; } | head -1 | cut -d'"' -f4
}
# membership key — verify, with one extra try in case of a typo
ATTEMPTS=2; [ -n "${MC_LICENSE:-}" ] && ATTEMPTS=1
VERIFIED=0
for try in $(seq 1 "$ATTEMPTS"); do
  KEY="${MC_LICENSE:-}"
  if [ -z "$KEY" ]; then
    [ "$try" -gt 1 ] && printf "  %sLet's try that once more.%s\n" "$DIM" "$Z"
    read -r -p "  Enter your membership key: " KEY </dev/tty || true
  fi
  KEY="$(printf '%s' "$KEY" | tr -d '[:space:]')"
  if [ -z "$KEY" ]; then printf '  %sNo key entered.%s\n' "$R" "$Z"; continue; fi
  printf '  %sVerifying membership...%s\n' "$DIM" "$Z"
  CODE="$(curl -sS -X POST "$WORKER_URL" \
          -H 'Content-Type: application/json' \
          -d "{\"license_key\":\"$KEY\",\"tutorial_slug\":\"$TUTORIAL_SLUG\"}" \
          -D "$TMP/head" -o "$TMP/body" -w '%{http_code}' 2>/dev/null || true)"
  CODE="${CODE:0:3}"; [ -n "$CODE" ] || CODE=000      # curl prints 000 itself when nothing answered
  if [ "$CODE" = "200" ]; then VERIFIED=1; break; fi
  # The server says WHY (install limit, renewal date, payment, wrong installer...): show its words as they
  # are. A Kit buyer at his install limit was told "check your key and your connection" twelve times
  # (2026-10-11). Only a reply that never came is a connection problem.
  ERR="$(_server_reason "$TMP/body")"
  LAST_CODE="$CODE"; LAST_ERR="$ERR"
  if [ -z "$ERR" ]; then
    case "$CODE" in
      000|5??) ERR="Could not reach the membership server. Check this machine's internet connection and try again." ;;
      *)       ERR="The membership server refused this key (HTTP $CODE) without saying why. Contact info@komputermechanic.com" ;;
    esac
  fi
  printf '  %s✗  %s%s\n' "$R" "$ERR" "$Z"
  # a typo is worth a second try; an install limit, a payment or an expired key is not
  case "$CODE:$LAST_ERR" in 403:*[Ii]nvalid*|403:) : ;; 403:*) break ;; esac
done
if [ "$VERIFIED" != "1" ]; then
  if [ -n "${LAST_ERR:-}" ]; then
    # the server's own words were printed above, as they are; just close the run
    printf '\n  %sNothing was installed. Questions: info@komputermechanic.com%s\n\n' "$DIM" "$Z"
  else
    case "${LAST_CODE:-000}" in
      000|5??) printf '\n  %s%sCould not reach the membership server.%s Check this machine'"'"'s internet connection and try again.\n\n' "$R" "$B" "$Z" ;;
      *)       printf '\n  %s%sYour key was not accepted.%s Contact info@komputermechanic.com\n\n' "$R" "$B" "$Z" ;;
    esac
  fi
  exit 1
fi

printf '  %s✓ Membership verified.%s\n' "$G" "$Z"

# unpack into the temp folder, stamp the key for traceability, run, then wipe
tar -xzf "$TMP/body" -C "$TMP" 2>/dev/null || { printf '  %sInstaller package was invalid.%s\n' "$R" "$Z"; exit 1; }
DIR="$TMP/agent-mission-control-installer"
[ -f "$DIR/install.sh" ] || { printf '  %sInstaller not found in package.%s\n' "$R" "$Z"; exit 1; }
CUSTOMER="$(grep -i '^x-km-customer:' "$TMP/head" | tr -d '\r' | awk '{print $2}')"
printf 'membership_key=%s\ncustomer=%s\ninstalled=%s\n' \
  "$KEY" "$CUSTOMER" "$(date -u +%FT%TZ 2>/dev/null || echo now)" > "$DIR/.license" 2>/dev/null || true

cd "$DIR"

# ---- pick the installer for this operating system ---------------------------
# macOS ships bash 3.2 (2007, frozen because bash 4 is GPLv3) and lacks GNU tools
# like `timeout` and `grep -P`, so it gets its own installer. The Linux install.sh
# is left exactly as tested.
#
# `uname -s` decides — it returns Darwin on every Mac and Linux on every Linux — but
# we SHOW the answer and let the buyer correct it, so a wrong guess can never silently
# run the wrong installer.
OS_NAME="$(uname -s 2>/dev/null || echo unknown)"
if [ "$OS_NAME" = "Darwin" ] && [ -f ./install-macos.sh ]; then
  PICKED="macos";  PICKED_LABEL="macOS"
else
  PICKED="linux";  PICKED_LABEL="Linux"
fi

# Show the friendly name only. "Darwin" is macOS's internal kernel name and means
# nothing to a buyer.
printf '\n  %sDetected system:%s %s%s%s\n' "$DIM" "$Z" "$B" "$PICKED_LABEL" "$Z"

# Only ask when there is a terminal AND a choice to make. Piped/unattended runs keep
# the detected answer. MC_OS=macos|linux overrides without prompting.
if [ -n "${MC_OS:-}" ]; then
  case "$MC_OS" in
    macos|Darwin|mac) PICKED="macos"; PICKED_LABEL="macOS" ;;
    linux|Linux)      PICKED="linux"; PICKED_LABEL="Linux" ;;
  esac
  printf '  %sMC_OS set — using %s.%s\n' "$DIM" "$PICKED_LABEL" "$Z"
elif [ -t 0 ] || [ -e /dev/tty ]; then
  read -r -p "  Is that correct? [Y/n]: " OS_OK </dev/tty || OS_OK=""
  case "$OS_OK" in
    [Nn]*)
      printf '  Which are you on?  %s1%s) Linux   %s2%s) macOS\n' "$B" "$Z" "$B" "$Z"
      read -r -p "  Enter 1 or 2: " OS_PICK </dev/tty || OS_PICK=""
      case "$OS_PICK" in
        2) PICKED="macos"; PICKED_LABEL="macOS" ;;
        *) PICKED="linux"; PICKED_LABEL="Linux" ;;
      esac
      ;;
  esac
fi

if [ "$PICKED" = "macos" ]; then
  if [ -f ./install-macos.sh ]; then
    INSTALLER="./install-macos.sh"
  else
    printf '  %sNo macOS installer in this package — falling back to the standard one.%s\n' "$R" "$Z"
    INSTALLER="./install.sh"
  fi
else
  INSTALLER="./install.sh"
fi
printf '  %sRunning the %s installer...%s\n' "$DIM" "$PICKED_LABEL" "$Z"

set +e
bash "$INSTALLER"
INSTALL_EXIT=$?
set -e

if [ "$INSTALL_EXIT" = "0" ]; then
  printf '\n  %sRecording activation...%s\n' "$DIM" "$Z"
  ACT_CODE="$(curl -sS -X POST "$WORKER_URL" \
    -H 'Content-Type: application/json' \
    -d "{\"license_key\":\"$KEY\",\"tutorial_slug\":\"$TUTORIAL_SLUG\",\"action\":\"activate\"}" \
    -o "$TMP/act" -w '%{http_code}' 2>/dev/null || echo 000)"
  if [ "$ACT_CODE" = "200" ]; then
    USED="$(grep -o '"used":[0-9]*' "$TMP/act" 2>/dev/null | cut -d: -f2 || true)"
    LIMIT="$(grep -o '"limit":[0-9]*' "$TMP/act" 2>/dev/null | cut -d: -f2 || true)"
    printf '  %s✓ Activation recorded (%s/%s installs used).%s\n' "$G" "${USED:-?}" "${LIMIT:-?}" "$Z"
  else
    printf '  %s⚠ Could not record activation — the install succeeded, but the count may not have updated.%s\n' "$R" "$Z"
  fi
else
  printf '\n  %s✗ Installation failed — no activation was recorded. Your install count was not affected.%s\n' "$R" "$Z"
  exit "$INSTALL_EXIT"
fi
