#!/bin/bash
# Grant Database Permissions - Run on Proxmox Host

VMID="${1:-10100}"
DB_NAME="${2:-dbis_core}"
DB_USER="${3:-dbis}"

echo "Granting permissions for $DB_USER on $DB_NAME (VMID: $VMID)..."

pct exec "$VMID" -- bash -c "su - postgres -c \"psql -d postgres << 'EOF'
GRANT CONNECT ON DATABASE $DB_NAME TO $DB_USER;
GRANT ALL PRIVILEGES ON DATABASE $DB_NAME TO $DB_USER;
ALTER USER $DB_USER CREATEDB;
EOF\""

pct exec "$VMID" -- bash -c "su - postgres -c \"psql -d $DB_NAME << 'EOF'
GRANT ALL ON SCHEMA public TO $DB_USER;
GRANT CREATE ON SCHEMA public TO $DB_USER;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO $DB_USER;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO $DB_USER;
EOF\""

echo "✅ Permissions granted!"
