#!/usr/bin/env bash
# One-shot deploy: upload the built .s9pk to FileBrowser, register it with the
# Start9 registry, and trigger a re-index so clients see the new version.
#
# Config is loaded from, in order:
#   1. Environment variables
#   2. $PROJECT_ROOT/.deploy.env  (gitignored; see .deploy.env.example)
#
# Required config:
#   FILEBROWSER_URL        — e.g. https://immense-voyage.local:51165
#   FILEBROWSER_USER       — your FileBrowser login
#   FILEBROWSER_PASS       — your FileBrowser password
#   START9_SERVER          — your Start9 server, e.g. https://immense-voyage.local:62185
#
# Optional config (sensible defaults):
#   FILEBROWSER_PATH       — path on FileBrowser to overwrite. Default: /websites/keysat-registry/recap_x86_64.s9pk
#   REGISTRY_URL           — registry JSON-RPC URL. Default: https://registry.keysat.xyz
#   REGISTRY_PUBLIC_URL    — public .s9pk URL registered with start-cli.
#                            Default: https://files.keysat.xyz/recap_x86_64.s9pk

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
ENV_FILE="$PROJECT_ROOT/.deploy.env"

if [ -f "$ENV_FILE" ]; then
  # shellcheck disable=SC1090
  set -a; source "$ENV_FILE"; set +a
fi

# --- Validate config ---
: "${FILEBROWSER_URL:?FILEBROWSER_URL is required (see bin/deploy.sh header)}"
: "${FILEBROWSER_USER:?FILEBROWSER_USER is required}"
: "${FILEBROWSER_PASS:?FILEBROWSER_PASS is required}"
: "${START9_SERVER:?START9_SERVER is required (e.g. https://immense-voyage.local:62185)}"

FILEBROWSER_PATH="${FILEBROWSER_PATH:-/websites/keysat-registry/recap_x86_64.s9pk}"
REGISTRY_URL="${REGISTRY_URL:-https://registry.keysat.xyz}"
REGISTRY_PUBLIC_URL="${REGISTRY_PUBLIC_URL:-https://files.keysat.xyz/recap_x86_64.s9pk}"

S9PK_FILE="$PROJECT_ROOT/recap_x86_64.s9pk"

if [ ! -f "$S9PK_FILE" ]; then
  echo "X  $S9PK_FILE not found. Run 'make x86' first." >&2
  exit 1
fi

# --- Discover current version from startos/versions ---
CURRENT_VAR="$(sed -nE "s/.*current:[[:space:]]*(v_[0-9_]+).*/\1/p" "$PROJECT_ROOT/startos/versions/index.ts" | head -1)"
if [ -n "$CURRENT_VAR" ]; then
  VERSION_DOT="$(echo "$CURRENT_VAR" | sed 's/^v_//; s/_/./g')"
  VERSION_FILE="$PROJECT_ROOT/startos/versions/v${VERSION_DOT}.ts"
  CURRENT_VERSION="$(sed -nE "s/.*version:[[:space:]]*'([^']+)'.*/\1/p" "$VERSION_FILE" | head -1)"
else
  CURRENT_VERSION="unknown"
fi

echo "==> Deploying recap $CURRENT_VERSION"
echo "    source : $S9PK_FILE"
echo "    upload : $FILEBROWSER_URL$FILEBROWSER_PATH"
echo "    public : $REGISTRY_PUBLIC_URL"
echo "    start9 : $START9_SERVER"
echo ""

# FileBrowser is typically on a *.local address with a self-signed cert, so
# curl needs -k (--insecure) to connect. Override with FILEBROWSER_CURL_OPTS if
# you've set up trust for the Start9 root CA.
FB_CURL_OPTS="${FILEBROWSER_CURL_OPTS:--k}"

# --- 1. Authenticate with FileBrowser ---
echo "[1/4] Authenticating with FileBrowser..."
LOGIN_BODY="$(printf '{"username":"%s","password":"%s"}' \
  "$(printf '%s' "$FILEBROWSER_USER" | sed 's/[\\"]/\\&/g')" \
  "$(printf '%s' "$FILEBROWSER_PASS" | sed 's/[\\"]/\\&/g')")"

TOKEN="$(curl $FB_CURL_OPTS -fsS -X POST "$FILEBROWSER_URL/api/login" \
  -H "Content-Type: application/json" \
  --data-raw "$LOGIN_BODY")" || {
    echo "X  FileBrowser login failed (check URL, username, password)" >&2
    exit 1
  }

if [ -z "$TOKEN" ]; then
  echo "X  FileBrowser login returned an empty token" >&2
  exit 1
fi

# --- 2. Upload .s9pk (override existing) ---
echo "[2/4] Uploading $(basename "$S9PK_FILE") ($(du -h "$S9PK_FILE" | cut -f1))..."
curl $FB_CURL_OPTS -fsS -X POST "$FILEBROWSER_URL/api/resources${FILEBROWSER_PATH}?override=true" \
  -H "X-Auth: $TOKEN" \
  -H "Content-Type: application/octet-stream" \
  --data-binary "@$S9PK_FILE" \
  -o /dev/null

# --- 3. Register with Start9 registry (adds manifest + pointer to public URL) ---
echo "[3/4] Registering package with registry..."
start-cli -r "$START9_SERVER" registry package add "$S9PK_FILE" --url "$REGISTRY_PUBLIC_URL"

# --- 4. Trigger registry re-index so clients see the new version ---
echo "[4/4] Re-indexing registry..."
curl -fsS -X POST "$REGISTRY_URL/rpc/v0" \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","method":"index","id":1}' \
  -o /dev/null

echo ""
echo "==> Done. recap $CURRENT_VERSION is live."
