#!/bin/bash

# PostgreSQL Connection Diagnostic Script
# Run this to diagnose your external PostgreSQL connection issues

echo "================================"
echo "PostgreSQL Connection Diagnostics"
echo "================================"
echo ""

# Check if DATABASE_URL is set
if [ -z "$DATABASE_URL" ]; then
    echo "❌ DATABASE_URL is not set"
    echo "Please set it: export DATABASE_URL='postgresql://user:pass@host:5432/db'"
    exit 1
fi

echo "✓ DATABASE_URL is set"
echo "URL: $DATABASE_URL (password hidden)"
echo ""

# Extract connection details
DB_URL=$DATABASE_URL
DB_HOST=$(echo $DB_URL | sed -n 's/.*@\([^:]*\).*/\1/p')
DB_PORT=$(echo $DB_URL | sed -n 's/.*:\([0-9]*\)\/.*/\1/p')
DB_USER=$(echo $DB_URL | sed -n 's/.*:\/\/\([^:]*\):.*/\1/p')
DB_NAME=$(echo $DB_URL | sed -n 's/.*\/\([^?]*\).*/\1/p')

echo "Connection Details:"
echo "  Host: $DB_HOST"
echo "  Port: $DB_PORT"
echo "  User: $DB_USER"
echo "  Database: $DB_NAME"
echo ""

# Test 1: Network connectivity
echo "Test 1: Network Connectivity"
echo "----------------------------"
if command -v nc &> /dev/null; then
    if nc -zv $DB_HOST $DB_PORT 2>&1 | grep -q succeeded; then
        echo "✓ Can reach $DB_HOST:$DB_PORT"
    else
        echo "❌ Cannot reach $DB_HOST:$DB_PORT"
        echo "Possible issues:"
        echo "  - PostgreSQL is not running"
        echo "  - Firewall blocking port $DB_PORT"
        echo "  - Wrong hostname/IP"
    fi
else
    echo "⚠ nc (netcat) not installed, skipping network test"
fi
echo ""

# Test 2: Try psql connection (if available)
echo "Test 2: PostgreSQL Connection"
echo "------------------------------"
if command -v psql &> /dev/null; then
    echo "Attempting connection..."
    if psql "$DATABASE_URL" -c "SELECT version();" 2>&1 | grep -q PostgreSQL; then
        echo "✓ Successfully connected to PostgreSQL!"
        echo ""
        echo "Getting PostgreSQL configuration..."
        echo ""
        
        # Check SSL status
        echo "SSL Status:"
        psql "$DATABASE_URL" -c "SHOW ssl;" 2>/dev/null || echo "  Could not check SSL status"
        echo ""
        
        # Check pg_hba.conf location
        echo "pg_hba.conf location:"
        psql "$DATABASE_URL" -c "SHOW hba_file;" 2>/dev/null || echo "  Could not get hba_file location"
        echo ""
        
        # Check data directory
        echo "Data directory:"
        psql "$DATABASE_URL" -c "SHOW data_directory;" 2>/dev/null || echo "  Could not get data directory"
        echo ""
        
        echo "✓ Your PostgreSQL is accessible!"
        echo ""
        echo "Next step: Check pg_hba.conf on your PostgreSQL server"
        
    else
        echo "❌ Connection failed"
        echo ""
        echo "Error details:"
        psql "$DATABASE_URL" -c "SELECT 1;" 2>&1 | head -5
        echo ""
        echo "Common issues:"
        echo "  1. Wrong username/password"
        echo "  2. Database doesn't exist"
        echo "  3. pg_hba.conf doesn't allow this connection"
        echo "  4. SSL required but not provided"
        echo ""
        echo "Try with SSL:"
        echo "  psql \"$DATABASE_URL?sslmode=require\""
    fi
else
    echo "⚠ psql not installed"
    echo "Install it to test connection: apt-get install postgresql-client"
fi
echo ""

# Test 3: Check DATABASE_SSL setting
echo "Test 3: SSL Configuration"
echo "-------------------------"
if [ -z "$DATABASE_SSL" ]; then
    echo "DATABASE_SSL: not set (no SSL)"
elif [ "$DATABASE_SSL" = "true" ]; then
    echo "DATABASE_SSL: true (SSL with self-signed certs)"
elif [ "$DATABASE_SSL" = "require" ]; then
    echo "DATABASE_SSL: require (SSL with valid certs)"
else
    echo "DATABASE_SSL: $DATABASE_SSL (unknown value)"
fi
echo ""

# Test 4: Get client IP
echo "Test 4: Client IP Address"
echo "-------------------------"
CLIENT_IP=$(curl -s ifconfig.me 2>/dev/null || echo "unknown")
echo "Your public IP: $CLIENT_IP"
echo "Docker container IP: varies (10.0.x.x or 172.x.x.x)"
echo ""
echo "Your pg_hba.conf needs to allow connections from Docker container IPs"
echo "Recommended entry: host  taskflow  taskflow  10.0.0.0/8  md5"
echo ""

# Summary
echo "================================"
echo "Summary & Recommendations"
echo "================================"
echo ""
echo "If connection failed with 'no pg_hba.conf entry' error:"
echo ""
echo "1. SSH into your PostgreSQL server:"
echo "   ssh your-postgres-server"
echo ""
echo "2. Find pg_hba.conf:"
echo "   sudo -u postgres psql -c \"SHOW hba_file;\""
echo ""
echo "3. Edit pg_hba.conf:"
echo "   sudo nano /etc/postgresql/16/main/pg_hba.conf"
echo ""
echo "4. Add this line:"
echo "   host    taskflow    taskflow    10.0.0.0/8    md5"
echo ""
echo "5. Reload PostgreSQL:"
echo "   sudo systemctl reload postgresql"
echo ""
echo "================================"
echo "OR use the bundled PostgreSQL:"
echo "================================"
echo ""
echo "Instead of fixing external PostgreSQL, use docker-compose:"
echo "   docker-compose up -d"
echo ""
echo "See QUICK-START-DOCKER-COMPOSE.md for full instructions"
echo ""
