#!/bin/bash
set -e

export VAULT_TOKEN="${VAULT_TOKEN:-}"

if [ -z "$VAULT_TOKEN" ]; then
    echo "Error: VAULT_TOKEN not set"
    exit 1
fi

get_secret() {
    docker exec -e VAULT_TOKEN="$VAULT_TOKEN" vault \
        vault kv get -field="$2" "aimpress/$1" 2>/dev/null
}

cat > init-scripts/01-create-databases.sql <<EOSQL
-- AImpress Database Init
-- Generated: $(date)

CREATE DATABASE authentik;
CREATE DATABASE supabase;
CREATE DATABASE n8n_shared;
CREATE DATABASE odoo;
CREATE DATABASE outline;
CREATE DATABASE vaultwarden;
CREATE DATABASE evolution;

CREATE USER authentik_user WITH PASSWORD '$(get_secret security/authentik db_password)';
CREATE USER supabase_user WITH PASSWORD '$(get_secret core/supabase db_password)';
CREATE USER n8n_user WITH PASSWORD '$(get_secret core/n8n db_password)';
CREATE USER odoo_user WITH PASSWORD '$(get_secret business/odoo db_password)';
CREATE USER outline_user WITH PASSWORD '$(get_secret business/outline db_password)';
CREATE USER vaultwarden_user WITH PASSWORD '$(get_secret security/vaultwarden db_password)';
CREATE USER evolution_user WITH PASSWORD '$(get_secret core/evolution db_password)';

GRANT ALL PRIVILEGES ON DATABASE authentik TO authentik_user;
ALTER DATABASE authentik OWNER TO authentik_user;

GRANT ALL PRIVILEGES ON DATABASE supabase TO supabase_user;
ALTER DATABASE supabase OWNER TO supabase_user;

GRANT ALL PRIVILEGES ON DATABASE n8n_shared TO n8n_user;
ALTER DATABASE n8n_shared OWNER TO n8n_user;

GRANT ALL PRIVILEGES ON DATABASE odoo TO odoo_user;
ALTER DATABASE odoo OWNER TO odoo_user;

GRANT ALL PRIVILEGES ON DATABASE outline TO outline_user;
ALTER DATABASE outline OWNER TO outline_user;

GRANT ALL PRIVILEGES ON DATABASE vaultwarden TO vaultwarden_user;
ALTER DATABASE vaultwarden OWNER TO vaultwarden_user;

GRANT ALL PRIVILEGES ON DATABASE evolution TO evolution_user;
ALTER DATABASE evolution OWNER TO evolution_user;

\c supabase
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
CREATE EXTENSION IF NOT EXISTS "pgcrypto";
CREATE EXTENSION IF NOT EXISTS "pg_trgm";
CREATE EXTENSION IF NOT EXISTS "btree_gin";
CREATE EXTENSION IF NOT EXISTS "btree_gist";

\c n8n_shared
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
CREATE EXTENSION IF NOT EXISTS "pgcrypto";

\c outline
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
CREATE EXTENSION IF NOT EXISTS "pg_trgm";
EOSQL

echo "✅ Generated init SQL"
