#!/bin/bash
# Update script to add PostgreSQL support to existing WHP installations

echo "==============================================="
echo "WHP PostgreSQL Support Installation"
echo "==============================================="

# Check if running as root
if [ "$EUID" -ne 0 ]; then 
    echo "Please run as root"
    exit 1
fi

# Function to generate secure password
generate_password() {
    tr -dc 'A-Za-z0-9!?&()-+=' </dev/urandom | head -c 18
}

# Create PostgreSQL data directory
echo "Creating PostgreSQL data directory..."
mkdir -p /docker/postgresql

# Generate PostgreSQL root password
echo "Generating PostgreSQL root password..."
postgres_password=$(generate_password)

# Start PostgreSQL container
echo "Starting PostgreSQL container..."
docker pull postgres:latest
docker run -d \
    --network client-net \
    --name postgresql \
    --env POSTGRES_PASSWORD="$postgres_password" \
    -v /docker/postgresql:/var/lib/postgresql/data:Z \
    -p 127.0.0.1:5432:5432 \
    --restart unless-stopped \
    postgres:latest

# Wait for PostgreSQL to be ready
echo "Waiting for PostgreSQL to be ready..."
sleep 10

# Test PostgreSQL connection
echo "Testing PostgreSQL connection..."
docker exec postgresql psql -U postgres -c "SELECT version();" >/dev/null 2>&1
if [ $? -eq 0 ]; then
    echo "✓ PostgreSQL is running and accessible"
else
    echo "✗ PostgreSQL connection test failed"
    echo "Check logs with: docker logs postgresql"
    exit 1
fi

# Store PostgreSQL login details in .pgpass format
echo "Storing PostgreSQL credentials..."
echo "127.0.0.1:5432:*:postgres:$postgres_password" > /root/.pgpass
chmod 600 /root/.pgpass

# Install PostgreSQL PHP module
echo "Installing PostgreSQL PHP module..."
dnf install -y php-pgsql

# Restart PHP-FPM to load the new module
echo "Restarting PHP-FPM to load PostgreSQL module..."
systemctl restart php-fpm

# Download Adminer for database management
echo "Installing Adminer for database management..."
if ! wget -q -O /docker/whp/web/adminer.php "https://www.adminer.org/latest.php"; then
    echo "⚠ Failed to download latest Adminer, trying alternative URL..."
    if ! wget -q -O /docker/whp/web/adminer.php "https://github.com/vrana/adminer/releases/download/v4.8.1/adminer-4.8.1.php"; then
        echo "⚠ Failed to download Adminer - database management interface may not work"
    else
        echo "✓ Adminer downloaded successfully (fallback version)"
    fi
else
    echo "✓ Adminer downloaded successfully (latest version)"
fi

# Apply database migrations
echo "Applying database migrations..."
mysql < /root/whp/sql/migrations/staging/001_postgresql_support.sql

# Update index.php to include PostgreSQL management
echo "Updating navigation menu..."
sed -i "/'database-management' => 'Database Management',/a\    'postgresql-management' => 'PostgreSQL Management'," /docker/whp/web/index.php

# Update permission manager to allow access to PostgreSQL management
echo "Updating permissions..."
sed -i "/'database-management' => array('all'), \/\/ All authenticated users/a\        'postgresql-management' => array('all'), \/\/ All authenticated users" /docker/whp/web/libs/permission_manager.php
sed -i "/'database-management' => array('all'),$/a\        'postgresql-management' => array('all')," /docker/whp/web/libs/permission_manager.php

# Restart Apache to apply changes
echo "Restarting Apache..."
systemctl restart httpd

# Display summary
echo ""
echo "==============================================="
echo "PostgreSQL Installation Complete!"
echo "==============================================="
echo ""
echo "PostgreSQL Details:"
echo "- Host: 127.0.0.1"
echo "- Port: 5432"
echo "- Username: postgres"
echo "- Password: $postgres_password"
echo "- Credentials stored in: /root/.pgpass"
echo ""
echo "Database Management:"
echo "- Adminer is available via the WHP interface"
echo "- PostgreSQL Management page provides full database management"
echo ""
echo "PostgreSQL container status:"
docker ps | grep postgresql >/dev/null 2>&1 && echo "✓ PostgreSQL container is running" || echo "✗ PostgreSQL container is not running"
echo ""
echo "To manage PostgreSQL databases, visit the PostgreSQL Management page in WHP."
echo "==============================================="