#!/bin/bash
# Master script to run all Chart of Accounts setup steps

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

echo "=========================================="
echo "Chart of Accounts - Complete Setup"
echo "=========================================="
echo ""

PROXMOX_HOST="192.168.11.10"
VMID="10100"

# Step 1: Try to grant permissions remotely
echo "Step 1: Granting database permissions..."
echo ""

if ssh -o ConnectTimeout=5 -o BatchMode=yes root@"$PROXMOX_HOST" exit 2>/dev/null; then
    echo "✅ SSH connection available - granting permissions..."
    ssh root@"$PROXMOX_HOST" "pct exec $VMID -- bash -c \"su - postgres -c \\\"psql -d postgres << 'SQL'
GRANT CONNECT ON DATABASE dbis_core TO dbis;
GRANT ALL PRIVILEGES ON DATABASE dbis_core TO dbis;
ALTER USER dbis CREATEDB;
SQL
\\\"\""
    
    ssh root@"$PROXMOX_HOST" "pct exec $VMID -- bash -c \"su - postgres -c \\\"psql -d dbis_core << 'SQL'
GRANT ALL ON SCHEMA public TO dbis;
GRANT CREATE ON SCHEMA public TO dbis;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO dbis;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO dbis;
SQL
\\\"\""
    echo "✅ Permissions granted"
else
    echo "⚠️  Cannot SSH to Proxmox host automatically"
    echo "   Please run this command manually on Proxmox host:"
    echo ""
    echo "   ssh root@$PROXMOX_HOST"
    echo "   pct exec $VMID -- bash -c \"su - postgres -c \\\"psql -d dbis_core << 'EOF'"
    echo "   GRANT CONNECT ON DATABASE dbis_core TO dbis;"
    echo "   GRANT ALL PRIVILEGES ON DATABASE dbis_core TO dbis;"
    echo "   ALTER USER dbis CREATEDB;"
    echo "   \\\\c dbis_core"
    echo "   GRANT ALL ON SCHEMA public TO dbis;"
    echo "   GRANT CREATE ON SCHEMA public TO dbis;"
    echo "   ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO dbis;"
    echo "   ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO dbis;"
    echo "   EOF\\\"\""
    echo ""
    read -p "Press Enter after permissions have been granted..."
fi

echo ""
echo "Step 2: Running migration..."
echo ""

./scripts/run-chart-of-accounts-migration.sh

echo ""
echo "=========================================="
echo "✅ Setup Complete!"
echo "=========================================="
