#!/usr/bin/env bash
# adom-mouser service container bootstrap.
# Run ONCE on a freshly created default-light container.
# Usage: MOUSER_API_KEY=<key> bash service/deploy.sh
#
# What it does:
#   1. Installs rustup if missing (default-light has no Rust)
#   2. Clones adom-inc/adom-mouser if not already present
#   3. Builds the binary and installs to /usr/local/bin
#   4. Persists MOUSER_API_KEY to /etc/environment (so cron inherits it)
#   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_MOUSER_REPO_URL:-https://github.com/adom-inc/adom-mouser.git}"
REPO_DIR="${ADOM_MOUSER_REPO:-$HOME/adom-mouser}"
PORT="${MOUSER_PORT:-8775}"

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-mouser 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-mouser /usr/local/bin/adom-mouser
ok "installed /usr/local/bin/adom-mouser ($(adom-mouser --version))"

# ── 4. API key → /etc/environment (so cron inherits it) ────────────
if [ -n "${MOUSER_API_KEY:-}" ]; then
  # Remove any prior MOUSER_API_KEY line, append the new one
  if grep -q '^MOUSER_API_KEY=' /etc/environment 2>/dev/null; then
    sudo sed -i '/^MOUSER_API_KEY=/d' /etc/environment
  fi
  echo "MOUSER_API_KEY=$MOUSER_API_KEY" | sudo tee -a /etc/environment >/dev/null
  ok "MOUSER_API_KEY persisted to /etc/environment"
else
  info "MOUSER_API_KEY not set in env — service will start but /health will show ok:false"
fi

# ── 5. Crons — watchdog + hourly smoke + daily live smoke ──────────
# Quota-aware: hourly smoke hits /health only (0 upstream calls).
# Live suite runs once/day at 13:00 UTC, ~2 upstream calls.
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-mouser-watchdog.log 2>&1"
SMOKE_CRON="20 * * * * $REPO_DIR/tests/cron-smoke.sh >> /tmp/adom-mouser-smoke.log 2>&1"
LIVE_CRON="0 13 * * * $REPO_DIR/tests/cron-smoke.sh --live >> /tmp/adom-mouser-smoke-live.log 2>&1"

(crontab -l 2>/dev/null | grep -v -E 'adom-mouser' || true; \
 echo "$WATCHDOG_CRON"; echo "$SMOKE_CRON"; echo "$LIVE_CRON") | crontab -
ok "crons installed (watchdog 2m · smoke hourly · live daily 13:00 UTC)"

chmod +x "$REPO_DIR/service/watchdog.sh" "$REPO_DIR/tests/cron-smoke.sh" "$REPO_DIR/tests/smoke.sh" "$REPO_DIR/tests/smoke-live.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-mouser.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 mouser"
echo "  2. curl the resulting public URL + /health to confirm"
echo "  3. Update ~/service-watcher/services.json with the new URL"
