#!/bin/sh
# Vault Initialization Script for BreakPilot
#
# This script initializes the KV v2 secrets engine and creates
# placeholder secrets for development.
#
# IMPORTANT: In production, replace these with real secrets via
# the Vault UI or CLI before deployment!

set -e

# Load root token from file (persistent storage mode)
if [ -z "$VAULT_TOKEN" ] && [ -f /vault/data/root-token ]; then
  export VAULT_TOKEN=$(cat /vault/data/root-token)
fi

echo "=== Vault Secret Initialization ==="
echo "Waiting for Vault to be ready..."

# Wait for Vault to be ready
until vault status > /dev/null 2>&1; do
    sleep 1
done

echo "Vault is ready. Initializing secrets..."

# Enable KV v2 secrets engine at 'secret/' (only if not already enabled)
if ! vault secrets list -format=json 2>/dev/null | grep -q '"secret/"'; then
  vault secrets enable -version=2 -path=secret kv
else
  echo "KV engine already enabled — skipping"
fi

# ================================================
# API Keys (PLACEHOLDER - Replace in production!)
# ================================================
echo "Creating API key secrets..."

vault kv put secret/breakpilot/api_keys/anthropic \
    value="REPLACE_WITH_REAL_ANTHROPIC_API_KEY"

vault kv put secret/breakpilot/api_keys/vast \
    value="REPLACE_WITH_REAL_VAST_API_KEY"

vault kv put secret/breakpilot/api_keys/tavily \
    value="REPLACE_WITH_REAL_TAVILY_API_KEY"

vault kv put secret/breakpilot/api_keys/stripe \
    value="REPLACE_WITH_REAL_STRIPE_SECRET_KEY"

vault kv put secret/breakpilot/api_keys/stripe_webhook \
    value="REPLACE_WITH_REAL_STRIPE_WEBHOOK_SECRET"

# ================================================
# Database Credentials
# ================================================
echo "Creating database secrets..."

vault kv put secret/breakpilot/database/postgres \
    username="breakpilot" \
    password="breakpilot123" \
    url="postgres://breakpilot:breakpilot123@postgres:5432/breakpilot_db?sslmode=disable"

# ================================================
# Authentication
# ================================================
echo "Creating auth secrets..."

# Generate random secrets for development
JWT_SECRET=$(openssl rand -hex 32 2>/dev/null || echo "dev-jwt-secret-replace-in-prod-32ch")
JWT_REFRESH_SECRET=$(openssl rand -hex 32 2>/dev/null || echo "dev-refresh-secret-replace-prod32")

vault kv put secret/breakpilot/auth/jwt \
    secret="$JWT_SECRET" \
    refresh_secret="$JWT_REFRESH_SECRET"

vault kv put secret/breakpilot/auth/keycloak \
    client_secret="REPLACE_WITH_KEYCLOAK_CLIENT_SECRET"

# ================================================
# Communication Services
# ================================================
echo "Creating communication secrets..."

vault kv put secret/breakpilot/communication/matrix \
    access_token="REPLACE_WITH_MATRIX_ACCESS_TOKEN" \
    db_password="synapse_secret_123"

vault kv put secret/breakpilot/communication/jitsi \
    app_secret="REPLACE_WITH_JITSI_APP_SECRET" \
    jicofo_password="jicofo_secret_123" \
    jvb_password="jvb_secret_123"

# ================================================
# Storage
# ================================================
echo "Creating storage secrets..."

vault kv put secret/breakpilot/storage/minio \
    access_key="minioadmin" \
    secret_key="minioadmin123"

# ================================================
# Infrastructure
# ================================================
echo "Creating infrastructure secrets..."

vault kv put secret/breakpilot/infra/vast \
    api_key="REPLACE_WITH_VAST_API_KEY" \
    instance_id="REPLACE_WITH_VAST_INSTANCE_ID" \
    control_api_key="REPLACE_WITH_CONTROL_API_KEY"

# ================================================
# Create policy for BreakPilot services
# ================================================
echo "Creating Vault policy..."

vault policy write breakpilot-backend - <<EOF
# BreakPilot Backend Policy
# Allows read access to all breakpilot secrets

path "secret/data/breakpilot/*" {
  capabilities = ["read", "list"]
}

path "secret/metadata/breakpilot/*" {
  capabilities = ["read", "list"]
}
EOF

vault policy write breakpilot-admin - <<EOF
# BreakPilot Admin Policy
# Full access to breakpilot secrets

path "secret/data/breakpilot/*" {
  capabilities = ["create", "read", "update", "delete", "list"]
}

path "secret/metadata/breakpilot/*" {
  capabilities = ["read", "list", "delete"]
}

path "secret/delete/breakpilot/*" {
  capabilities = ["update"]
}

path "secret/undelete/breakpilot/*" {
  capabilities = ["update"]
}
EOF

# ================================================
# Create AppRole for services
# ================================================
echo "Enabling AppRole auth method..."

vault auth enable approle 2>/dev/null || echo "AppRole already enabled"

# Create role for backend service
vault write auth/approle/role/breakpilot-backend \
    token_policies="breakpilot-backend" \
    token_ttl=1h \
    token_max_ttl=4h \
    secret_id_ttl=0

# Get role-id for backend
ROLE_ID=$(vault read -field=role_id auth/approle/role/breakpilot-backend/role-id)
echo ""
echo "=== AppRole Credentials ==="
echo "Role ID: $ROLE_ID"
echo ""
echo "Generate a secret-id with:"
echo "  vault write -f auth/approle/role/breakpilot-backend/secret-id"
echo ""

echo "=== Vault Initialization Complete ==="
echo ""
echo "IMPORTANT: Replace placeholder secrets before production deployment!"
echo ""
echo "To view secrets:"
echo "  vault kv list secret/breakpilot/"
echo "  vault kv get secret/breakpilot/api_keys/anthropic"
echo ""
echo "To update a secret:"
echo "  vault kv put secret/breakpilot/api_keys/anthropic value='sk-ant-xxx...'"
