#!/bin/sh
# VPS Firstboot Path Test
# Validates the full module pipeline with TARGET=vps pre-baked vars.
# No root required. Runs in a tmpdir sandbox.
#
# Usage: sh firstboot/vps-path-test.sh

set -eu

SCRIPT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
TESTDIR="${SCRIPT_DIR}/tmp/vps-path-test-$$"
mkdir -p "$TESTDIR"

# ── Mock filesystem ──
mkdir -p "$TESTDIR/etc/pkg/repos"
mkdir -p "$TESTDIR/etc/profile.d"
mkdir -p "$TESTDIR/var/log"
mkdir -p "$TESTDIR/var/cache/pkg/bastille"
mkdir -p "$TESTDIR/usr/local/share/clawdie-iso/packages"

# Mock Clawdie-AI tarball (matches ISO layout: Clawdie-AI/ → /home/clawdie/clawdie-ai)
mkdir -p "$TESTDIR/Clawdie-AI/node_modules"
cat > "$TESTDIR/Clawdie-AI/package.json" <<'PKG'
{"name":"clawdie-ai","version":"1.0.2","scripts":{"install":"echo '[npm] Services ready'"}}
PKG

# Mock justfile (firstboot deploy runs: just install)
cat > "$TESTDIR/Clawdie-AI/justfile" <<'EOF'
set dotenv-load

install *args="":
  @echo "[just] Services ready"
EOF

# Mock tarball
tar -czf "$TESTDIR/clawdie-ai.tar.gz" -C "$TESTDIR" Clawdie-AI 2>/dev/null || true

PASS=0
FAIL=0
check() {
  if [ "$1" = "0" ]; then
    echo "  PASS: $2"
    PASS=$((PASS + 1))
  else
    echo "  FAIL: $2"
    FAIL=$((FAIL + 1))
  fi
}

echo ""
echo "============================================================"
echo " VPS Firstboot Path Test"
echo " Simulates TARGET=vps with pre-baked vars (no wizard)"
echo "============================================================"
echo ""

# ── VPS pre-baked vars (minimum required) ──
export TARGET="vps"
export ASSISTANT_NAME="VpsClawdie"
export AGENT_DOMAIN="clawdie.home.arpa"
export AGENT_GENDER="f"
export TZ="Europe/Ljubljana"
export SYSTEM_LOCALE="sl_SI.UTF-8"
export DISPLAY_LOCALE="sl_SI.UTF-8"
export ASSISTANT_LOCALE="sl_SI.UTF-8"
export KEYMAP="sl.kbd"

# ── Optional VPS vars ──
export FEATURE_TAILSCALE="NO"
export FEATURE_GITEA="NO"
export CODE_HOSTING_MODE="git"
export FEATURE_GIT="YES"
export LOCAL_LLM_PROVIDER="none"
export FEATURE_OLLAMA="NO"
export FEATURE_LLAMA_CPP="NO"
export FEATURE_OLLAMA_HPP="NO"
export DEFAULT_PKG_BRANCH="latest"
export SSH_PUBLIC_KEY=""
export PI_TUI_PROVIDER=""
export PI_TUI_MODEL=""
export FEATURE_TELEGRAM="NO"
export TELEGRAM_BOT_TOKEN=""
export TELEGRAM_ADMIN_IDS=""
export TAILSCALE_AUTHKEY=""
export ZAI_API_KEY=""
export OPENROUTER_API_KEY=""
export ANTHROPIC_API_KEY=""
export EMBED_BASE_URL=""
export EMBED_MODEL=""
export EMBED_API_KEY=""
export EMBED_DIMENSIONS=""

# ── Test guards ──
export SHELL_ENV_TEST=1
export SHELL_PKG_TEST=1
export SHELL_GPU_TEST=1
export SHELL_NVIDIA_TEST=1
export SHELL_SYSTEM_TEST=1
export SHELL_TAILSCALE_TEST=1
export SHELL_DEPLOY_TEST=1

# ── Sandbox overrides ──
export CLAWDIE_HOME="$TESTDIR/home/clawdie"
export CLAWDIE_AI_DIR="$CLAWDIE_HOME/clawdie-ai"
export CLAWDIE_TARBALL="$TESTDIR/clawdie-ai.tar.gz"
export PKG_CONF_DIR="$TESTDIR/etc/pkg/repos"
export FREEBSD_REPO_CONF="$PKG_CONF_DIR/FreeBSD.conf"
export CLAWDIE_USB_REPO_CONF="$PKG_CONF_DIR/Clawdie-USB.conf"
export USB_PKG_PATH="$TESTDIR/usr/local/share/clawdie-iso/packages"
export BASTILLE_PKG_CACHE="$TESTDIR/var/cache/pkg/bastille"
export RC_CONF="$TESTDIR/etc/rc.conf"
export HOSTNAME_FILE="$TESTDIR/etc/hostname"
export PROFILE_DIR="$TESTDIR/etc/profile.d"
export LOG_FILE="$TESTDIR/var/log/cloud-test.log"
export PROGRESS_FILE="$TESTDIR/var/log/cloud-test.progress"
export ENV_FILE="$CLAWDIE_HOME/.env"

touch "$LOG_FILE" "$PROGRESS_FILE" "$RC_CONF"

# ── Source all modules ──
. "$SCRIPT_DIR/firstboot/shell-env.sh" 2>/dev/null
. "$SCRIPT_DIR/firstboot/shell-pkg.sh" 2>/dev/null
. "$SCRIPT_DIR/firstboot/shell-gpu.sh" 2>/dev/null
. "$SCRIPT_DIR/firstboot/shell-nvidia.sh" 2>/dev/null
. "$SCRIPT_DIR/firstboot/shell-system.sh" 2>/dev/null
. "$SCRIPT_DIR/firstboot/shell-tailscale.sh" 2>/dev/null
. "$SCRIPT_DIR/firstboot/shell-deploy.sh" 2>/dev/null

# ──────────────────────────────────────────────────────────────
echo "[1/7] Cloud validation"
_ok=0
[ -n "${ASSISTANT_NAME:-}" ] || _ok=1
[ -n "${AGENT_DOMAIN:-}" ] || _ok=1
[ -n "${TZ:-}" ] || _ok=1
check "$_ok" "Required pre-baked vars present (ASSISTANT_NAME, AGENT_DOMAIN, TZ)"

# ──────────────────────────────────────────────────────────────
echo ""
echo "[2/7] GPU detection (headless — should not crash)"
export DETECTED_GPU=""
clawdie_shell_gpu_detect 2>/dev/null
check "0" "GPU detect completed on headless system"

# ──────────────────────────────────────────────────────────────
echo ""
echo "[3/7] Package config"
clawdie_shell_pkg_setup 2>/dev/null
[ -f "$FREEBSD_REPO_CONF" ]; check "$?" "FreeBSD repo config written"
[ -f "$CLAWDIE_USB_REPO_CONF" ]; check "$?" "USB repo config written"
if grep -q "usr/local/share/clawdie-iso/packages" "$CLAWDIE_USB_REPO_CONF" 2>/dev/null; then
  check "0" "USB repo points to SHARE/packages (offline path correct)"
else
  check "1" "USB repo points to SHARE/packages (offline path correct)"
fi

# ──────────────────────────────────────────────────────────────
echo ""
echo "[4/7] Env generation"
clawdie_shell_env_generate 2>/dev/null
[ -f "$ENV_FILE" ]; check "$?" ".env file created"

# Check key vars are in .env (quotes included in format)
for var_check in \
  'ASSISTANT_NAME="VpsClawdie"' \
  'AGENT_DOMAIN="clawdie.home.arpa"' \
  'TZ="Europe/Ljubljana"' \
  'CODE_HOSTING_MODE="git"' \
  'FEATURE_GITEA="NO"' \
  'FEATURE_TAILSCALE="NO"' \
  'EMBED_API_KEY=""' \
  'EMBED_DIMENSIONS="1024"'; do
  if grep -qF "$var_check" "$ENV_FILE" 2>/dev/null; then
    check "0" "$var_check in .env"
  else
    check "1" "$var_check in .env"
  fi
done

# ──────────────────────────────────────────────────────────────
echo ""
echo "[5/7] System config"
clawdie_shell_system_config >/dev/null 2>&1
[ -f "$HOSTNAME_FILE" ]; check "$?" "Hostname file created"
if [ -f "$HOSTNAME_FILE" ]; then
  _hn=$(cat "$HOSTNAME_FILE")
  if echo "$_hn" | grep -q "clawdie.home.arpa"; then
    check "0" "Hostname = $_hn"
  else
    check "1" "Hostname = $_hn (expected *clawdie.cloud*)"
  fi
fi

# ──────────────────────────────────────────────────────────────
echo ""
echo "[6/7] Tailscale (disabled)"
clawdie_shell_tailscale_setup >/dev/null 2>&1
check "0" "Tailscale skipped (FEATURE_TAILSCALE=NO)"

# ──────────────────────────────────────────────────────────────
echo ""
echo "[7/7] Deploy"
clawdie_shell_deploy 2>/dev/null
[ -f "$CLAWDIE_AI_DIR/package.json" ]; check "$?" "Clawdie-AI deployed"
[ -f "$CLAWDIE_AI_DIR/.env" ]; check "$?" ".env copied into clawdie-ai"

# ──────────────────────────────────────────────────────────────
echo ""
echo "============================================================"
echo "  PASS: $PASS  FAIL: $FAIL"
echo "============================================================"

# Cleanup
rm -rf "$TESTDIR"

if [ "$FAIL" -eq 0 ]; then
  echo ""
  echo "  All cloud path checks passed."
  exit 0
else
  echo ""
  echo "  $FAIL check(s) failed — review output above."
  exit 1
fi
