#!/usr/bin/env bash
# adom-digikey service container bootstrap.
# Run ONCE on a freshly created default-light container.
# Usage: DIGIKEY_CLIENT_ID=<id> DIGIKEY_CLIENT_SECRET=<secret> bash service/deploy.sh
#
# What it does:
#   1. Installs rustup if missing (default-light has no Rust)
#   2. Clones adom-inc/adom-digikey if not already present
#   3. Builds the binary and installs to /usr/local/bin
#   4. Persists DIGIKEY_CLIENT_ID + DIGIKEY_CLIENT_SECRET to /etc/environment (so cron inherits them)
#   5. Installs the cron line for watchdog.sh (every 2 min)
#   6. Kicks off the first run and verifies /health

set -euo pipefail

REPO_URL="${ADOM_DIGIKEY_REPO_URL:-https://github.com/adom-inc/adom-digikey.git}"
REPO_DIR="${ADOM_DIGIKEY_REPO:-$HOME/adom-digikey}"
PORT="${DIGIKEY_PORT:-8777}"

ok()   { printf '  \033[32m✓\033[0m %s\n' "$1"; }
info() { printf '  \033[2m%s\033[0m\n' "$1"; }
fail() { printf '  \033[31m✗\033[0m %s\n' "$1" >&2; exit 1; }

echo "== adom-digikey service deploy =="

# ── 1. Rust toolchain ──────────────────────────────────────────────
if ! command -v cargo >/dev/null; then
  info "installing rustup (default-light has no Rust)..."
  curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | \
    sh -s -- -y --default-toolchain stable --profile minimal
  . "$HOME/.cargo/env"
  ok "rustup installed ($(rustc --version))"
else
  ok "rustc already present ($(rustc --version))"
fi

# ── 2. Clone the repo ──────────────────────────────────────────────
if [ -d "$REPO_DIR/.git" ]; then
  ok "repo already cloned at $REPO_DIR"
  cd "$REPO_DIR"
  git fetch --quiet origin main && git reset --hard origin/main
  ok "repo fast-forwarded to origin/main"
else
  info "cloning $REPO_URL..."
  git clone "$REPO_URL" "$REPO_DIR" || fail "git clone failed (is the repo private? Set up gh auth first)"
  ok "cloned to $REPO_DIR"
  cd "$REPO_DIR"
fi

# ── 3. Build + install ─────────────────────────────────────────────
info "building release binary (takes 1-2 min)..."
cargo build --release
sudo install -m 0755 target/release/adom-digikey /usr/local/bin/adom-digikey
ok "installed /usr/local/bin/adom-digikey ($(adom-digikey --version))"

# ── 4. API credentials → /etc/environment (OAuth2 needs BOTH id+secret) ──
for var in DIGIKEY_CLIENT_ID DIGIKEY_CLIENT_SECRET; do
  val="${!var:-}"
  if [ -n "$val" ]; then
    sudo sed -i "/^${var}=/d" /etc/environment 2>/dev/null || true
    echo "${var}=${val}" | sudo tee -a /etc/environment >/dev/null
    ok "${var} persisted to /etc/environment"
  else
    info "${var} not set — service will start but /health will show ok:false"
  fi
done

# ── 5. Crons — watchdog + hourly smoke ─────────────────────────────
command -v jq >/dev/null || sudo apt-get install -y -qq jq >/dev/null 2>&1 || true

WATCHDOG_CRON="*/2 * * * * $REPO_DIR/service/watchdog.sh >> /tmp/adom-digikey-watchdog.log 2>&1"
SMOKE_CRON="25 * * * * $REPO_DIR/tests/cron-smoke.sh >> /tmp/adom-digikey-smoke.log 2>&1"

(crontab -l 2>/dev/null | grep -v -E 'adom-digikey' || true; \
 echo "$WATCHDOG_CRON"; echo "$SMOKE_CRON") | crontab -
ok "crons installed (watchdog 2m · smoke hourly :25)"

chmod +x "$REPO_DIR/service/watchdog.sh" "$REPO_DIR/tests/cron-smoke.sh" "$REPO_DIR/tests/smoke.sh" 2>/dev/null || true

# ── 6. First run + health check ────────────────────────────────────
info "running watchdog to start the service..."
bash "$REPO_DIR/service/watchdog.sh" || true
sleep 3

HEALTH=$(curl -sf --max-time 5 "http://127.0.0.1:$PORT/health" || true)
if [ -z "$HEALTH" ]; then
  fail "service did not come up on port $PORT — check /tmp/adom-digikey.log"
fi
ok "service healthy on port $PORT"
echo "  $(echo "$HEALTH" | head -c 200)"

echo
echo "Next steps (run from your MAIN container, not here):"
echo "  1. adom-cli carbon containers port-add <this-slug> --port $PORT --prefix digikey"
echo "  2. curl the resulting public URL + /health to confirm"
echo "  3. Update ~/service-watcher/services.json with the new URL"
