#!/bin/bash
# setup_authentik.sh — Deploy Authentik + Caddy on neon-64gb
# Uses existing Postgres (arxiv-pg) and Redis on neon.
#
# Run from any node with SSH access to neon:
#   bash scripts/setup_authentik.sh
#
# Authentik listens on:
#   HTTP  → port 30001 (Caddy at auth.neon.lan proxies to this)
#   HTTPS → port 30100 (reserved for future direct TLS)

set -euo pipefail
NEON="allaun@100.92.88.64"

echo "=== Step 1: Create authentik database ==="
ssh "$NEON" "
psql -h localhost -U postgres -tc \"SELECT 1 FROM pg_database WHERE datname='authentik'\" | grep -q 1 || \
  psql -h localhost -U postgres -c 'CREATE DATABASE authentik'
"

echo "=== Step 2: Generate shared secret key ==="
AUTH_KEY=$(python3 -c "import secrets; print(secrets.token_hex(32))")

echo "=== Step 3: Pull image ==="
ssh "$NEON" "podman pull ghcr.io/goauthentik/server:latest"

echo "=== Step 4: Remove old containers ==="
ssh "$NEON" "podman rm -f authentik-server authentik-worker 2>/dev/null || true"

echo "=== Step 5: Start server (port 30001) ==="
ssh "$NEON" "
podman run -d --name authentik-server \
  --network host \
  -e AUTHENTIK_SECRET_KEY='$AUTH_KEY' \
  -e AUTHENTIK_POSTGRESQL__NAME=authentik \
  -e AUTHENTIK_POSTGRESQL__USER=postgres \
  -e AUTHENTIK_POSTGRESQL__HOST=localhost \
  -e AUTHENTIK_POSTGRESQL__PORT=5432 \
  -e AUTHENTIK_POSTGRESQL__PASSWORD=postgres \
  -e AUTHENTIK_REDIS__HOST=localhost \
  -e AUTHENTIK_REDIS__PORT=6379 \
  -e AUTHENTIK_LISTEN__HTTP=0.0.0.0:30001 \
  ghcr.io/goauthentik/server:latest server
"

echo "=== Step 6: Start worker ==="
ssh "$NEON" "
podman run -d --name authentik-worker \
  --network host \
  -e AUTHENTIK_SECRET_KEY='$AUTH_KEY' \
  -e AUTHENTIK_POSTGRESQL__NAME=authentik \
  -e AUTHENTIK_POSTGRESQL__USER=postgres \
  -e AUTHENTIK_POSTGRESQL__HOST=localhost \
  -e AUTHENTIK_POSTGRESQL__PORT=5432 \
  -e AUTHENTIK_POSTGRESQL__PASSWORD=postgres \
  -e AUTHENTIK_REDIS__HOST=localhost \
  -e AUTHENTIK_REDIS__PORT=6379 \
  ghcr.io/goauthentik/server:latest worker
"

echo "=== Step 7: Wait for migrations ==="
sleep 10

echo "=== Status ==="
ssh "$NEON" "
podman ps --filter name=auth --format '{{.Names}} {{.Status}}'
curl -s -o /dev/null -w 'HTTP port 30001: %{http_code}\n' http://localhost:30001/
"

echo "=== Done ==="
echo "  Authentik: http://localhost:30001 (neon) or http://auth.neon.lan via Caddy"
echo "  Setup wizard at first visit creates the admin account."
echo ""
echo "  To route via Caddy (if desired):"
echo "    ssh $NEON 'cat > ~/caddy/Caddyfile << EOF"
echo "  auth.neon.lan {"
echo "      reverse_proxy localhost:30001"
echo "  }"
echo "  EOF""
echo "    ssh $NEON 'podman restart caddy'"
