#!/usr/bin/env bash
#
# Retrace — Lumena Technologies internal installer.
# Authenticates via Cloudflare Access (a one-time code is emailed to you),
# then downloads and installs the private build.
#
#   curl -fsSL https://get.lumenatech.ai | bash                 # install
#   curl -fsSL https://get.lumenatech.ai | bash -s -- --uninstall   # remove
#   curl -fsSL https://get.lumenatech.ai | bash -s -- --reinstall   # remove + install
#
set -euo pipefail

# The Access-protected download URL (the R2-backed Worker). Set this to your host.
DOWNLOAD_URL="${RETRACE_DOWNLOAD_URL:-https://download.lumenatech.ai}"
RETRACE_HOME="${RETRACE_HOME:-$HOME/.retrace-private}"
BIN_DIR="${RETRACE_BIN_DIR:-$HOME/.local/bin}"
CMD="${RETRACE_CMD:-retrace-private}"

say(){ printf '\033[1;36m==>\033[0m %s\n' "$1"; }
die(){ printf '\033[1;31merror:\033[0m %s\n' "$1" >&2; exit 1; }

# --- uninstall -------------------------------------------------------------
# Fully remove retrace-private: home, commands, bundled Node shims, and the
# shell-profile PATH line (same handling as the public installer).
uninstall_retrace_private() {
  say "Removing $CMD..."
  pkill -f "$RETRACE_HOME/responses-chat-proxy" 2>/dev/null || true
  pkill -f "$RETRACE_HOME" 2>/dev/null || true
  rm -f "$BIN_DIR/$CMD" "$BIN_DIR/${CMD}-admin"
  # node/npm/npx shims only if they point into RETRACE_HOME (ours)
  for l in node npm npx; do
    t="$(readlink "$BIN_DIR/$l" 2>/dev/null || true)"
    case "$t" in "$RETRACE_HOME"/*) rm -f "$BIN_DIR/$l" ;; esac
  done
  rm -rf "$RETRACE_HOME"
  # strip the PATH block we may have added to the shell profile (public parity).
  for rc in "$HOME/.zshrc" "$HOME/.bashrc"; do
    if [ -f "$rc" ] && grep -q '# >>> retrace PATH >>>' "$rc" 2>/dev/null; then
      sed -i.retracebak '/# >>> retrace PATH >>>/,/# <<< retrace PATH <<</d' "$rc" && rm -f "$rc.retracebak"
    fi
  done
  say "$CMD removed ($RETRACE_HOME, commands, PATH entry)."
}

DO_UNINSTALL=0; DO_REINSTALL=0
for arg in "$@"; do
  case "$arg" in
    --uninstall) DO_UNINSTALL=1 ;;
    --reinstall) DO_UNINSTALL=1; DO_REINSTALL=1 ;;
  esac
done
if [ "$DO_UNINSTALL" = "1" ]; then
  uninstall_retrace_private
  if [ "$DO_REINSTALL" != "1" ]; then
    printf '\n  Done. Reinstall any time:  curl -fsSL https://get.lumenatech.ai | bash\n\n'
    exit 0
  fi
  say "Reinstalling a fresh copy..."
fi

[ "$(uname -s)" = "Darwin" ] || die "macOS only for v1."

# 1. Ensure cloudflared (handles the Access browser login + token). Auto-install
#    the official binary directly — no Homebrew / admin required.
BIN_DIR="${RETRACE_BIN_DIR:-$HOME/.local/bin}"
CFD="cloudflared"
command -v cloudflared >/dev/null 2>&1 || { [ -x "$BIN_DIR/cloudflared" ] && CFD="$BIN_DIR/cloudflared"; }
if ! command -v "$CFD" >/dev/null 2>&1 && [ ! -x "$BIN_DIR/cloudflared" ]; then
  say "Installing cloudflared (one-time, no admin needed)…"
  case "$(uname -m)" in arm64|aarch64) CFARCH=arm64 ;; *) CFARCH=amd64 ;; esac
  url="https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-darwin-${CFARCH}.tgz"
  mkdir -p "$BIN_DIR"
  TMPD="$(mktemp -d)"
  if curl -fsSL "$url" -o "$TMPD/cfd.tgz" && tar -xzf "$TMPD/cfd.tgz" -C "$TMPD" 2>/dev/null; then
    install -m 0755 "$TMPD/cloudflared" "$BIN_DIR/cloudflared" 2>/dev/null || { chmod +x "$TMPD/cloudflared"; mv "$TMPD/cloudflared" "$BIN_DIR/cloudflared"; }
    CFD="$BIN_DIR/cloudflared"
  else
    rm -rf "$TMPD"
    die "could not download cloudflared ($url). Install it manually and re-run: https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/"
  fi
  rm -rf "$TMPD"
  export PATH="$BIN_DIR:$PATH"
fi
# Resolve the cloudflared to use (PATH copy if present, else the one we installed).
if command -v cloudflared >/dev/null 2>&1; then CFD="cloudflared"; else CFD="$BIN_DIR/cloudflared"; fi
[ -x "$BIN_DIR/cloudflared" ] && CFD="$BIN_DIR/cloudflared"
command -v "$CFD" >/dev/null 2>&1 || [ -x "$CFD" ] || die "cloudflared is not available."

# 2. Authenticate via Cloudflare Access — opens your browser, you enter the
#    one-time code emailed to your address.
say "Opening your browser to sign in — enter the code emailed to you."
"$CFD" access login "$DOWNLOAD_URL" >/dev/null 2>&1 || true
TOKEN="$("$CFD" access token -app="$DOWNLOAD_URL" 2>/dev/null || true)"
[ -n "${TOKEN:-}" ] || die "authentication failed or was cancelled."

# 3. Download the private bundle with the Access token.
TMP="$(mktemp -d)"; trap 'rm -rf "$TMP"' EXIT
say "Downloading the Lumena build…"
curl -fsSL -H "cf-access-token: $TOKEN" "$DOWNLOAD_URL" -o "$TMP/bundle.tar.gz" \
  || die "download failed (are you on the allowlist?)."
tar -xzf "$TMP/bundle.tar.gz" -C "$TMP" || die "could not unpack the bundle."

# 4. Run the internal installer bundled inside.
[ -f "$TMP/install-internal.sh" ] || die "bundle is missing install-internal.sh."
say "Installing…"
bash "$TMP/install-internal.sh"
