#!/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

# Detect platform for the right bundle + the right cloudflared build.
# macOS ships an x86_64 binary that runs on Apple Silicon via Rosetta, so all
# Macs use the macos-x86_64 bundle; Linux is x86_64-only for now.
case "$(uname -s)" in
  Darwin) CFOS=darwin; PLATFORM=macos-x86_64 ;;
  Linux)  CFOS=linux ;;
  *) die "Unsupported OS: $(uname -s) (macOS and Linux only)." ;;
esac
if [ "$CFOS" = linux ]; then
  case "$(uname -m)" in x86_64|amd64) PLATFORM=linux-x86_64 ;; *) die "Linux is x86_64 only for now (got $(uname -m))." ;; esac
fi
case "$(uname -m)" in arm64|aarch64) CFARCH=arm64 ;; *) CFARCH=amd64 ;; esac

# 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)…"
  mkdir -p "$BIN_DIR"; TMPD="$(mktemp -d)"; ok=0
  if [ "$CFOS" = darwin ]; then
    # macOS: a .tgz containing the binary.
    url="https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-darwin-${CFARCH}.tgz"
    curl -fsSL "$url" -o "$TMPD/cfd.tgz" && tar -xzf "$TMPD/cfd.tgz" -C "$TMPD" 2>/dev/null && ok=1
  else
    # Linux: a raw binary.
    url="https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-${CFARCH}"
    curl -fsSL "$url" -o "$TMPD/cloudflared" && ok=1
  fi
  if [ "$ok" = 1 ] && [ -f "$TMPD/cloudflared" ]; then
    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: 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 ($PLATFORM)…"
curl -fsSL -H "cf-access-token: $TOKEN" "$DOWNLOAD_URL/?platform=$PLATFORM" -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"
