#!/bin/bash
# Script to create/fix PostgreSQL user and database
# Run this on the PostgreSQL server or with superuser access

echo "=== PostgreSQL User Setup Script ==="
echo ""

# Load environment variables if .env exists
if [ -f .env ]; then
    source .env 2>/dev/null || export $(cat .env | xargs)
fi

# Default values
DB_USER="${DB_USER:-dev}"
DB_NAME="${DB_NAME:-internet}"
DB_HOST="${DB_HOST:-localhost}"

echo "This script will:"
echo "  1. Create PostgreSQL user: $DB_USER"
echo "  2. Create database: $DB_NAME"
echo "  3. Grant privileges"
echo ""
read -p "Enter new password for user '$DB_USER': " -s NEW_PASSWORD
echo ""
read -p "Confirm password: " -s CONFIRM_PASSWORD
echo ""

if [ "$NEW_PASSWORD" != "$CONFIRM_PASSWORD" ]; then
    echo "❌ Passwords do not match!"
    exit 1
fi

if [ -z "$NEW_PASSWORD" ]; then
    echo "❌ Password cannot be empty!"
    exit 1
fi

echo ""
echo "Connecting to PostgreSQL..."
echo "You may be prompted for PostgreSQL superuser password (postgres user)"

# Create user if it doesn't exist
psql -h "$DB_HOST" -U postgres -c "
DO \$\$
BEGIN
    IF NOT EXISTS (SELECT FROM pg_user WHERE usename = '$DB_USER') THEN
        CREATE USER $DB_USER WITH PASSWORD '$NEW_PASSWORD';
        RAISE NOTICE 'User $DB_USER created';
    ELSE
        ALTER USER $DB_USER WITH PASSWORD '$NEW_PASSWORD';
        RAISE NOTICE 'User $DB_USER password updated';
    END IF;
END
\$\$;
" 2>&1

if [ $? -ne 0 ]; then
    echo "❌ Failed to create/update user"
    exit 1
fi

# Create database if it doesn't exist
psql -h "$DB_HOST" -U postgres -c "
SELECT 'CREATE DATABASE $DB_NAME'
WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = '$DB_NAME')\gexec
" 2>&1

# Grant privileges
psql -h "$DB_HOST" -U postgres -c "
ALTER DATABASE $DB_NAME OWNER TO $DB_USER;
GRANT ALL PRIVILEGES ON DATABASE $DB_NAME TO $DB_USER;
" 2>&1

if [ $? -eq 0 ]; then
    echo ""
    echo "✅ User and database setup complete!"
    echo ""
    echo "Update your .env file with:"
    echo "DB_PASSWORD=$NEW_PASSWORD"
    echo ""
else
    echo "❌ Failed to grant privileges"
    exit 1
fi

