#!/usr/bin/env bash
set -euo pipefail

podman rm -f $(podman ps -aq) 2>/dev/null || true

podman run -d --name postgres --network host --restart always \
  -e POSTGRES_PASSWORD=postgres \
  docker.io/library/postgres:16 -c max_connections=200

for i in $(seq 1 30); do
  pg_isready -h localhost -q && break
  sleep 2
done

psql -h localhost -U postgres -c "CREATE DATABASE authentik" 2>/dev/null || true
psql -h localhost -U postgres -d authentik -c "CREATE EXTENSION IF NOT EXISTS citext" 2>/dev/null || true

podman run -d --name redis --network host --restart always docker.io/library/redis:7-alpine

for role in server worker; do
  podman run -d --name "authentik-$role" --network host --restart always \
    -e AUTHENTIK_SECRET_KEY="authentik-secret-key" \
    -e AUTHENTIK_POSTGRESQL__HOST=localhost \
    -e AUTHENTIK_POSTGRESQL__NAME=authentik \
    -e AUTHENTIK_POSTGRESQL__USER=postgres \
    -e AUTHENTIK_POSTGRESQL__PASSWORD=postgres \
    -e AUTHENTIK_REDIS__HOST=localhost \
    -e AUTHENTIK_REDIS__PORT=6379 \
    ghcr.io/goauthentik/server:2026.5.3 "$role"
done

echo "Stack started"
podman ps --format "table {{.Names}}\t{{.Status}}"
echo "Authentik: http://localhost:9000"
loginctl enable-linger
