#!/bin/bash

set -e

echo "════════════════════════════════════════════════════════"
echo "  Authelia OIDC / JWT Signing Setup (PKCS#8)"
echo "════════════════════════════════════════════════════════"
echo ""

# Check Docker
if ! docker info > /dev/null 2>&1; then
    echo "❌ Docker is not running"
    exit 1
fi

echo "✓ Docker is running"
echo ""

mkdir -p secrets certs

echo "Generating secrets..."
openssl rand -hex 32 > secrets/jwt_secret
openssl rand -hex 32 > secrets/session_secret
openssl rand -base64 64 | tr -d '\n' > secrets/storage_encryption_key
openssl rand -hex 32 > secrets/oidc_hmac_secret
chmod 600 secrets/*
echo "✓ Secrets generated"

echo "Generating TLS certificate..."
openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
  -keyout certs/authelia.key \
  -out certs/authelia.crt \
  -subj "/CN=skxu7cjbbsb7.share.staging.zrok.io" \
  -addext "subjectAltName=DNS:skxu7cjbbsb7.share.staging.zrok.io,DNS:localhost,IP:127.0.0.1" \
  > /dev/null 2>&1
echo "✓ TLS certificate created"

echo "Generating PKCS#8 OIDC signing key..."
openssl genpkey -algorithm RSA \
  -pkeyopt rsa_keygen_bits:2048 \
  -out certs/oidc.pkcs8.key

openssl pkey -in certs/oidc.pkcs8.key -pubout \
  -out certs/oidc.pub

openssl req -new -x509 \
  -key certs/oidc.pkcs8.key \
  -out certs/oidc.cert \
  -days 365 \
  -subj "/CN=authelia-oidc"

chmod 600 certs/*.key
chmod 644 certs/*.crt certs/*.cert certs/*.pub

echo "✓ OIDC signing keys created"

echo ""
echo "════════════════════════════════════════════════════════"
echo " COPY THIS INTO config.yml"
echo "════════════════════════════════════════════════════════"
echo ""

cat <<EOF
identity_providers:
  oidc:
    jwks:
      - key_id: "main-signing-key"
        algorithm: "RS256"
        use: "sig"
        key: |
$(sed 's/^/          /' certs/oidc.pkcs8.key)
        certificate_chain: |
$(sed 's/^/          /' certs/oidc.cert)
EOF

echo ""
echo "✓ Configuration ready"
echo ""
echo "Next steps:"
echo "1. Paste above into config.yml"
echo "2. docker-compose up -d"
echo "3. curl -k https://127.0.0.1:9091/jwks.json"
