#!/usr/bin/env bash
# ============================================================================
#  VENARI - Installer  ·  by KomputerMechanic
#  The curl one-liner target. Verifies your membership key, shows the terms, then runs the real
#  installer in a temporary folder that is wiped afterwards. The installer is never stored on your machine.
#
#     curl -fsSL https://venari-quiet-lantern.komputermechanic.com | bash
#
#  Running it again on a machine that has Venari brings it up to date: your websites, searches,
#  clients and keys are kept.
# ============================================================================
set -euo pipefail
WORKER_URL="https://venari-quiet-lantern.komputermechanic.com"
TUTORIAL_SLUG="venari"

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

printf '\n  %s%sKomputerMechanic  ~  VENARI%s\n' "$B" "$ACC" "$Z"
printf '  %sDesign search + website builder for your Hermes · installer%s\n\n' "$DIM" "$Z"

command -v curl >/dev/null || { printf '  %scurl is required.%s\n' "$R" "$Z"; exit 1; }
# said BEFORE the key is asked for, so nobody types a key for a machine Venari does not run on yet
case "$(uname -s 2>/dev/null)" in
  Linux|Darwin) : ;;
  *) printf '  %sVenari runs on Linux and macOS.%s No key was asked for and nothing was changed.\n\n' "$B" "$Z"; exit 1 ;;
esac

# macOS has no `timeout`: perl's alarm does the same job (the signal ends the command after N seconds)
if ! command -v timeout >/dev/null 2>&1; then
timeout() { local s="${1%s}"; shift; perl -e 'alarm shift; exec @ARGV' "$s" "$@"; }
fi
TMP="$(mktemp -d)"; trap 'rm -rf "$TMP"' EXIT

# TESTS ONLY: VEN_LOCAL_TARBALL=<file> uses a package already on this machine (no activation recorded).
if [ -n "${VEN_LOCAL_TARBALL:-}" ]; then
  cp "$VEN_LOCAL_TARBALL" "$TMP/body" || { printf '  %sNo package at %s%s\n' "$R" "$VEN_LOCAL_TARBALL" "$Z"; exit 1; }
  : > "$TMP/head"; KEY="local-test"
  printf '  %sTest run: using the local package %s%s\n' "$DIM" "$VEN_LOCAL_TARBALL" "$Z"
else
_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
}
LAST_ERR=""; LAST_CODE=""
ATTEMPTS=2; [ -n "${VEN_LICENSE:-}" ] && ATTEMPTS=1
VERIFIED=0
for try in $(seq 1 "$ATTEMPTS"); do
  KEY="${VEN_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 --retry 3 --retry-delay 2 --retry-all-errors -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
  if [ "$CODE" = "200" ]; then VERIFIED=1; break; fi
  # the server says WHY (install limit, renewal, payment...): its words, as they are
  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"
  case "$CODE:$LAST_ERR" in 403:*[Ii]nvalid*|403:) : ;; 403:*) break ;; esac
done
if [ "$VERIFIED" != "1" ]; then
  if [ -n "$LAST_ERR" ]; then 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"
fi

tar -xzf "$TMP/body" -C "$TMP" 2>/dev/null || { printf '  %sInstaller package was invalid.%s\n' "$R" "$Z"; exit 1; }
DIR="$TMP/venari-installer"
[ -f "$DIR/install.sh" ] || { printf '  %sInstaller not found in package.%s\n' "$R" "$Z"; exit 1; }

# ---- the terms: accepted BEFORE anything on this machine is touched -----------------------------------
if [ -f "$DIR/payload/TERMS.txt" ]; then
  _tw=70; _te=""; _ti=0; while [ "$_ti" -lt $((_tw + 2)) ]; do _te="${_te}╌"; _ti=$((_ti + 1)); done
  printf '\n  %s┌%s┐%s\n' "$ACC" "$_te" "$Z"
  printf '  %s┊%s %sPLEASE READ  -  LICENSE, DISCLAIMER & TERMS%s\n  %s┊%s\n' "$ACC" "$Z" "$B" "$Z" "$ACC" "$Z"
  awk -v RS= '{gsub(/\n/," "); print; print ""}' "$DIR/payload/TERMS.txt" | fold -s -w "$_tw" | sed "s/^/  ${ACC}┊${Z} /"
  printf '  %s└%s┘%s\n' "$ACC" "$_te" "$Z"
  if [ -n "${VEN_YES:-}" ]; then
    printf '  %s(VEN_YES set: the terms are accepted for this unattended run)%s\n' "$DIM" "$Z"
  elif { : </dev/tty; } 2>/dev/null; then
    _acc=""; read -r -p "  Type Y to accept and continue, anything else to stop: " _acc </dev/tty || _acc=""
    case "$_acc" in [Yy]|[Yy][Ee][Ss]) printf '  %s✓ Terms accepted.%s\n' "$G" "$Z" ;;
      *) printf '\n  %sThe terms were not accepted. Nothing was installed and no install was used.%s\n\n' "$R" "$Z"; exit 1 ;; esac
  else
    printf '\n  %sThere is no terminal here to accept the terms.%s Run the installer in a terminal.\n\n' "$R" "$Z"; exit 1
  fi
  export VEN_TERMS_ACCEPTED=1
fi

# ---- Hermes in a Docker container on this server (Hostinger's VPS image and the like) ----------------
# There `hermes` is not on the server itself: it lives in a container, data at /opt/data, as its own user.
# Every running container is ASKED whether it holds Hermes (never guessed from its name). With a choice to
# make the buyer picks; unattended runs keep the server itself, or need VEN_CONTAINER_NAME=<name>.
_hermes_on_host() { command -v hermes >/dev/null 2>&1 || [ -x "$HOME/.local/bin/hermes" ] || [ -x /usr/local/bin/hermes ]; }
_ctr_is_hermes() {
  timeout 10 docker exec "$1" sh -c 'command -v hermes >/dev/null 2>&1 || [ -n "${HERMES_HOME:-}" ] \
    || ls /opt/data/config.yaml /home/*/.hermes/config.yaml /root/.hermes/config.yaml >/dev/null 2>&1' >/dev/null 2>&1
}
_tty() { { : </dev/tty; } 2>/dev/null; }
CTR=""; NAMES=()
if command -v docker >/dev/null 2>&1 && docker ps >/dev/null 2>&1; then
  while IFS= read -r _n; do [ -n "$_n" ] && _ctr_is_hermes "$_n" && NAMES+=("$_n"); done < <(docker ps --format '{{.Names}}' 2>/dev/null || true)
  if [ -n "${VEN_CONTAINER_NAME:-}" ]; then
    docker ps --format '{{.Names}}' | grep -qx "$VEN_CONTAINER_NAME" \
      || { printf '\n  %sNo running container called %s.%s Running ones:\n' "$R" "$VEN_CONTAINER_NAME" "$Z"; docker ps --format '     {{.Names}}  {{.Image}}'; echo; exit 1; }
    CTR="$VEN_CONTAINER_NAME"
  elif [ "${#NAMES[@]}" -gt 0 ]; then
    _HOST=""; _hermes_on_host && _HOST=1
    if [ -z "$_HOST" ] && [ "${#NAMES[@]}" -eq 1 ]; then
      CTR="${NAMES[0]}"
      printf '\n  %sYour Hermes runs in the Docker container %s%s: Venari goes in there with it.\n' "$B" "$CTR" "$Z"
      if _tty && [ -z "${VEN_YES:-}" ]; then
        read -r -p "  Install Venari into '$CTR'? [Y/n]: " _ok </dev/tty || _ok=""
        case "$_ok" in [Nn]*) printf '\n  Nothing installed.\n\n'; exit 0 ;; esac
      fi
    elif ! _tty || [ -n "${VEN_YES:-}" ]; then
      if [ -z "$_HOST" ]; then
        printf '\n  %sMore than one Hermes container and nobody to ask.%s Name one and re-run:  VEN_CONTAINER_NAME=<name>\n\n' "$R" "$Z"; exit 1
      fi
      printf '\n  %sHermes containers here too (%s), but no one to ask: Venari goes on this server itself.%s\n' "$DIM" "${NAMES[*]}" "$Z"
    else
      printf '\n  %sWhere should Venari go?%s\n' "$B" "$Z"
      [ -n "$_HOST" ] && printf '     %s0)%s this server %s(the Hermes installed on it)%s\n' "$B" "$Z" "$DIM" "$Z"
      _i=0; while [ "$_i" -lt "${#NAMES[@]}" ]; do printf '     %s%d)%s the Docker container %s\n' "$B" $((_i+1)) "$Z" "${NAMES[$_i]}"; _i=$((_i+1)); done
      _pick=""; _tries=0
      while [ "$_tries" -lt 3 ]; do
        read -r -p "  Your choice: " _pick </dev/tty || _pick=""
        if [ "$_pick" = 0 ] && [ -n "$_HOST" ]; then CTR=""; break
        elif printf '%s' "$_pick" | grep -qE '^[0-9]+$' && [ "$_pick" -ge 1 ] && [ "$_pick" -le "${#NAMES[@]}" ]; then CTR="${NAMES[$((_pick-1))]}"; break; fi
        printf '  %sPick a number from the list.%s\n' "$R" "$Z"; _tries=$((_tries+1)); _pick=""
      done
      [ -z "$_pick" ] && { printf '\n  Nothing installed: no choice made.\n\n'; exit 1; }
    fi
  fi
fi

# ---- Hermes this installer set up last time, whose model step did not finish ----------------------------
# (the marker is still in Hermes' data): the setup continues at the model instead of installing on a model that
# never answered
_MADE=""
if [ -n "$CTR" ] && docker exec "$CTR" sh -c 'test -f "${HERMES_HOME:-/opt/data}/.venari-hermes-setup"' >/dev/null 2>&1; then
  printf '\n  %sHermes is in container %s, but its setup did not finish last time.%s Continuing with your AI model.\n' "$B" "$CTR" "$Z"
  _HD_OUT="$(VEN_HD_RESUME="$CTR" bash "$DIR/payload/hermes-docker.sh")" || { printf '\n  %sHermes could not be set up (see above). Nothing of Venari was installed and no install was used.%s\n\n' "$R" "$Z"; exit 1; }
  _MADE=1
fi

# ---- no Hermes anywhere: set it up first ---------------------------------------------------------------
# A Linux server gets Hermes Agent (Nous Research, MIT) in Docker, the way NEXORA and Accordo Pro do it; a Mac
# gets it natively (no Docker there). Venari then installs on it like on any Hermes.
_HN_RESUME=""
[ -z "$CTR" ] && _hermes_on_host && [ "$(uname -s)" = Darwin ] && [ -f "${HERMES_HOME:-$HOME/.hermes}/.venari-hermes-setup" ] && _HN_RESUME=1
if [ -z "$CTR" ] && { ! _hermes_on_host || [ -n "$_HN_RESUME" ]; }; then
  if [ -z "$_HN_RESUME" ]; then
    printf '\n  %sThere is no Hermes on this machine yet.%s Venari runs on Hermes Agent (free, open source, by Nous Research).\n' "$B" "$Z"
    if [ "$(uname -s)" = Linux ]; then printf '  The installer sets it up for you first, in Docker.\n'; else printf '  The installer sets it up for you first.\n'; fi
    _go="y"
    if [ -z "${VEN_YES:-}" ] && _tty; then read -r -p "  Install Hermes Agent now? [Y/n]: " _go </dev/tty || _go=""; fi
    case "${_go:-y}" in [Nn]*) printf '\n  Nothing installed. Install Hermes yourself, then run this installer again.\n\n'; exit 0 ;; esac
  fi
  if [ "$(uname -s)" = Linux ]; then
    _HD_OUT="$(bash "$DIR/payload/hermes-docker.sh")" || { printf '\n  %sHermes could not be set up (see above). Nothing of Venari was installed and no install was used.%s\n\n' "$R" "$Z"; exit 1; }
    CTR="$(printf '%s\n' "$_HD_OUT" | sed -n 's/^CONTAINER=//p' | tail -1)"
    [ -n "$CTR" ] || { printf '  %sHermes was set up but did not report its container.%s\n' "$R" "$Z"; exit 1; }
    docker ps >/dev/null 2>&1 || docker() { sudo docker "$@"; }      # a fresh Docker may still need sudo here
  else
    _HN_OUT="$(VEN_HN_RESUME="$_HN_RESUME" bash "$DIR/payload/hermes-native.sh")" || { printf '\n  %sHermes could not be set up (see above). Nothing of Venari was installed and no install was used.%s\n\n' "$R" "$Z"; exit 1; }
    _HN_BIN="$(printf '%s\n' "$_HN_OUT" | sed -n 's/^HERMES=//p' | tail -1)"
    [ -n "$_HN_BIN" ] || { printf '  %sHermes was set up but did not report where it is.%s\n' "$R" "$Z"; exit 1; }
    export PATH="$(dirname "$_HN_BIN"):$PATH"
  fi
  _MADE=1
fi

# ---- a Hermes that is already in use: a dedicated server is recommended ------------------------------------
# Venari brings its own team (scouts, a design team, a website builder) in its own Hermes home: it never changes
# the owner's agents, but long builds share the machine's processor and the model's usage. So when this Hermes
# already has agents or a history of its own, the buyer is told, and decides. Unattended: VEN_FORCE=1.
_lived() {   # prints "<extra agents> <conversations>" for the Hermes Venari is going into
  local _py='import os, sqlite3, sys
h = sys.argv[1]
p = [d for d in os.listdir(os.path.join(h, "profiles")) if not d.startswith("venari-")] if os.path.isdir(os.path.join(h, "profiles")) else []
n = 0
try:
    n = sqlite3.connect("file:" + os.path.join(h, "state.db") + "?mode=ro", uri=True).execute("select count(*) from sessions").fetchone()[0]
except Exception:
    pass
print(len(p), n)'
  if [ -n "$CTR" ]; then docker exec "$CTR" sh -c 'h="${HERMES_HOME:-/opt/data}"; [ -d "$h/venari" ] && exit 3; for p in /opt/hermes/.venv/bin/python3 python3; do command -v "$p" >/dev/null 2>&1 && exec "$p" -c "$0" "$h"; done' "$_py" 2>/dev/null
  else [ -d "${VEN_DIR:-$HOME/venari}" ] && return 3; python3 -c "$_py" "${HERMES_HOME:-$HOME/.hermes}" 2>/dev/null; fi
}
if [ -z "$_MADE" ]; then
  _lrc=0; _L="$(_lived)" || _lrc=$?      # 3 = Venari is here already (an update): never stop the script (set -e)
  _NA="${_L%% *}"; _NS="${_L##* }"
  if [ "$_lrc" != 3 ] && { [ "${_NA:-0}" -gt 0 ] || [ "${_NS:-0}" -gt 20 ]; } 2>/dev/null; then
    printf '\n  %sThis Hermes is already in use%s (%s agent profile(s), %s conversations).\n' "$B" "$Z" "${_NA:-0}" "${_NS:-0}"
    printf '  Venari brings a team of its own (scouts, a design team, a website builder). It installs next to your\n'
    printf '  agents and never changes them, but its builds share this machine and your model'"'"'s usage.\n'
    printf '  %sRecommended: a dedicated server for Venari.%s\n' "$B" "$Z"
    if [ -n "${VEN_FORCE:-}" ]; then printf '  %s(VEN_FORCE set: installing here anyway)%s\n' "$DIM" "$Z"
    elif _tty && [ -z "${VEN_YES:-}" ]; then
      read -r -p "  Install Venari on this Hermes anyway? [y/N]: " _f </dev/tty || _f=""
      case "$_f" in [Yy]*) : ;; *) printf '\n  Nothing installed and no install was used. Run this one-liner on a dedicated server.\n\n'; exit 0 ;; esac
    else
      printf '\n  Nothing installed. To install here anyway, run it again with VEN_FORCE=1.\n\n'; exit 1
    fi
  fi
fi

set +e
if [ -n "$CTR" ]; then
  # the user Hermes runs as in there: whoever owns its data folder (uid 10000 on the official image)
  _CHH="$(docker exec "$CTR" sh -c 'printf %s "${HERMES_HOME:-/opt/data}"' 2>/dev/null || echo /opt/data)"
  _CUSER="$(docker exec "$CTR" sh -c "ls -ld '$_CHH' | awk '{print \$3}'" 2>/dev/null || echo hermes)"
  printf '  %sCopying the installer into %s (it runs there as %s)...%s\n' "$DIM" "$CTR" "$_CUSER" "$Z"
  docker cp "$TMP/body" "$CTR:/tmp/venari-installer.tar.gz" >/dev/null 2>&1 \
    || { printf '  %sCould not copy the installer into the container.%s\n' "$R" "$Z"; exit 1; }
  docker exec "$CTR" chown "$_CUSER" /tmp/venari-installer.tar.gz >/dev/null 2>&1 || true
  # the tunnel the buyer opens goes through THIS server: name it, since inside the container it is unknowable
  [ -n "${VEN_VPS_HOST:-}" ] || VEN_VPS_HOST="$(id -un)@$( { hostname -I 2>/dev/null || true; } | awk '{print $1}')"
  case "$VEN_VPS_HOST" in *@) VEN_VPS_HOST="" ;; esac
  _ENVARGS=(-e VEN_CONTAINER=1 -e VEN_TERMS_ACCEPTED=1)
  # a container this installer made publishes the studio on this server's 127.0.0.1: the link goes through that
  _PUB="$(docker port "$CTR" 2>/dev/null | grep -oE '127\.0\.0\.1:[0-9]+' | head -1 | cut -d: -f2)"
  [ -n "$_PUB" ] && _ENVARGS+=(-e "VEN_PUBLISHED=$_PUB")
  [ -n "$VEN_VPS_HOST" ] && _ENVARGS+=(-e "VEN_VPS_HOST=$VEN_VPS_HOST")
  while IFS= read -r _kv; do _ENVARGS+=(-e "$_kv"); done < <(env | grep -E '^VEN_[A-Z_]+=' | grep -vE '^VEN_(LICENSE|CONTAINER|CONTAINER_NAME|TERMS_ACCEPTED|VPS_HOST|LOCAL_TARBALL)=' || true)
  _CSCRIPT='rm -rf /tmp/venari-installer && tar -xzf /tmp/venari-installer.tar.gz -C /tmp \
    && cd /tmp/venari-installer && bash install.sh; rc=$?
    rm -rf /tmp/venari-installer /tmp/venari-installer.tar.gz; exit $rc'
  # the installer's questions read the terminal: hand it ours. Never this script's own stdin (curl's pipe).
  if _tty; then docker exec -it -u "$_CUSER" "${_ENVARGS[@]}" "$CTR" bash -c "$_CSCRIPT" </dev/tty
  else docker exec -i -u "$_CUSER" -e VEN_YES=1 "${_ENVARGS[@]}" "$CTR" bash -c "$_CSCRIPT" </dev/null; fi
  INSTALL_EXIT=$?
  docker exec "$CTR" rm -f /tmp/venari-installer.tar.gz >/dev/null 2>&1 || true
  # the private link for every device: Tailscale on this server, to the published studio port
  if [ "$INSTALL_EXIT" = 0 ] && [ -n "$_PUB" ] && [ "${VEN_TAILNET:-1}" != 0 ] && command -v tailscale >/dev/null 2>&1 && tailscale status >/dev/null 2>&1; then
    _TP="${VEN_TS_PORT:-8476}"; _SU=""; [ "$(id -u)" = 0 ] || _SU=sudo
    if tailscale serve status 2>/dev/null | grep -q ":$_TP"; then printf '  %sTailnet port %s is already used for something else: left as it is.%s\n' "$DIM" "$_TP" "$Z"
    elif tailscale serve --bg --https="$_TP" "http://127.0.0.1:$_PUB" >/dev/null 2>&1 || $_SU tailscale serve --bg --https="$_TP" "http://127.0.0.1:$_PUB" >/dev/null 2>&1; then
      _TSN="$(tailscale status --json 2>/dev/null | python3 -c 'import json,sys;print(json.load(sys.stdin)["Self"]["DNSName"].rstrip("."))' 2>/dev/null)"
      [ -n "$_TSN" ] && printf '  %s✓ Private link for all your devices (your tailnet only):%s %shttps://%s:%s%s\n\n' "$G" "$Z" "$B" "$_TSN" "$_TP" "$Z"
    fi
  fi
else
  bash "$DIR/install.sh"
  INSTALL_EXIT=$?
fi
set -e

if [ -n "${VEN_LOCAL_TARBALL:-}" ]; then
  [ "$INSTALL_EXIT" = "0" ] && printf '  %s✓ Installed (test run: no activation recorded).%s\n\n' "$G" "$Z"; exit "$INSTALL_EXIT"
elif [ "$INSTALL_EXIT" = "0" ]; then
  printf '  %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\n' "$G" "${USED:-?}" "${LIMIT:-?}" "$Z"
  else
    printf '  %s⚠ Could not record activation: the install succeeded, but the count may not have updated.%s\n\n' "$R" "$Z"
  fi
else
  printf '\n  %s✗ Installation failed: no activation was recorded. Your install count was not affected.%s\n\n' "$R" "$Z"
  exit "$INSTALL_EXIT"
fi
