#!/bin/bash

# Script to fix database password from VMID 5000 (Blockscout)
# This script provides commands to run as root in VMID 5000

set -euo pipefail

VMID=5000

echo "=========================================="
echo "Database Password Fix for VMID 5000"
echo "=========================================="
echo ""
echo "This script provides commands to fix the database password"
echo "for the explorer backend from within VMID 5000 (Blockscout)."
echo ""
echo "Choose one of the following options:"
echo ""

# Option 1: Direct commands
echo "=== OPTION 1: Run Commands Directly in VMID 5000 ==="
echo ""
echo "Execute these commands from the Proxmox host:"
echo ""
echo "# Step 1: Check if PostgreSQL is accessible"
echo "pct exec $VMID -- pg_isready -h localhost -p 5432 -U explorer || echo 'PostgreSQL not accessible'"
echo ""
echo "# Step 2: Reset password (if postgres user is accessible)"
echo "pct exec $VMID -- psql -h localhost -p 5432 -U postgres << 'SQL_EOF'"
echo "DO \\\$\\\$"
echo "BEGIN"
echo "    IF NOT EXISTS (SELECT FROM pg_user WHERE usename = 'explorer') THEN"
echo "        CREATE USER explorer WITH PASSWORD 'changeme';"
echo "    ELSE"
echo "        ALTER USER explorer WITH PASSWORD 'changeme';"
echo "    END IF;"
echo "END"
echo "\\\$\\\$;"
echo "SELECT 'CREATE DATABASE explorer OWNER explorer'"
echo "WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = 'explorer')\\gexec"
echo "GRANT ALL PRIVILEGES ON DATABASE explorer TO explorer;"
echo "SQL_EOF"
echo ""
echo "# Step 3: Verify connection"
echo "pct exec $VMID -- bash -c \"PGPASSWORD=changeme psql -h localhost -p 5432 -U explorer -d explorer -c 'SELECT 1;'\""
echo ""

# Option 2: Interactive script
echo "=== OPTION 2: Interactive Fix Script ==="
echo ""
echo "Copy and paste this into VMID 5000 (pct enter $VMID or pct exec $VMID -- bash):"
echo ""
cat << 'INLINE_SCRIPT'
#!/bin/bash
# Run this script inside VMID 5000 as root

DB_HOST="${DB_HOST:-localhost}"
DB_PORT="${DB_PORT:-5432}"
DB_USER="explorer"
DB_PASSWORD="changeme"
DB_NAME="explorer"

echo "Fixing database password for explorer backend..."
echo "Database Host: $DB_HOST"
echo "Database Port: $DB_PORT"
echo ""

# Check if psql is available
if ! command -v psql &> /dev/null; then
    echo "Installing PostgreSQL client..."
    apt-get update -qq
    apt-get install -y postgresql-client
fi

# Check connectivity
echo "Checking database connectivity..."
if ! pg_isready -h "$DB_HOST" -p "$DB_PORT" >/dev/null 2>&1; then
    echo "ERROR: Cannot connect to PostgreSQL at $DB_HOST:$DB_PORT"
    echo "Please check:"
    echo "  1. PostgreSQL is running"
    echo "  2. Database host is correct"
    echo "  3. Network connectivity"
    exit 1
fi

echo "PostgreSQL is accessible"

# Try to connect as postgres user
echo "Attempting to reset password..."
if psql -h "$DB_HOST" -p "$DB_PORT" -U postgres -c "SELECT 1;" >/dev/null 2>&1; then
    # Reset password
    psql -h "$DB_HOST" -p "$DB_PORT" -U postgres << SQL_EOF
DO \$\$
BEGIN
    IF NOT EXISTS (SELECT FROM pg_user WHERE usename = '$DB_USER') THEN
        CREATE USER $DB_USER WITH PASSWORD '$DB_PASSWORD';
        RAISE NOTICE 'User $DB_USER created';
    ELSE
        ALTER USER $DB_USER WITH PASSWORD '$DB_PASSWORD';
        RAISE NOTICE 'User $DB_USER password updated';
    END IF;
END
\$\$;

SELECT 'CREATE DATABASE $DB_NAME OWNER $DB_USER'
WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = '$DB_NAME')\gexec

GRANT ALL PRIVILEGES ON DATABASE $DB_NAME TO $DB_USER;
SQL_EOF

    # Verify
    echo ""
    echo "Verifying connection..."
    if PGPASSWORD="$DB_PASSWORD" psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$DB_NAME" -c "SELECT 1;" >/dev/null 2>&1; then
        echo "✅ SUCCESS: Database password fixed and connection verified!"
    else
        echo "❌ ERROR: Connection verification failed"
        exit 1
    fi
else
    echo "ERROR: Cannot connect as postgres user"
    echo "You may need to:"
    echo "  1. Use a different database host"
    echo "  2. Provide postgres password"
    echo "  3. Check PostgreSQL authentication settings"
    exit 1
fi
INLINE_SCRIPT

echo ""
echo "=== OPTION 3: If Database is in Docker Container ==="
echo ""
echo "If Blockscout uses Docker Compose, run these commands in VMID 5000:"
echo ""
cat << 'DOCKER_SCRIPT'
# Find postgres container
POSTGRES_CONTAINER=$(docker ps | grep postgres | awk '{print $1}')

# Reset password
docker exec -it $POSTGRES_CONTAINER psql -U postgres << SQL_EOF
DO \$\$
BEGIN
    IF NOT EXISTS (SELECT FROM pg_user WHERE usename = 'explorer') THEN
        CREATE USER explorer WITH PASSWORD 'changeme';
    ELSE
        ALTER USER explorer WITH PASSWORD 'changeme';
    END IF;
END
\$\$;

SELECT 'CREATE DATABASE explorer OWNER explorer'
WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = 'explorer')\gexec

GRANT ALL PRIVILEGES ON DATABASE explorer TO explorer;
SQL_EOF
DOCKER_SCRIPT

echo ""
echo "=========================================="
echo "After fixing the password, restart the backend:"
echo "  (from the host running the backend API)"
echo "  kill \$(cat /tmp/explorer_backend.pid) 2>/dev/null"
echo "  ./scripts/start-backend-service.sh"
echo "=========================================="

