#!/usr/bin/env bash
# Setup PostgreSQL for Sankofa on r630-01
# VMID: 7803, IP: 10.160.0.13

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/.env.r630-01" 2>/dev/null || true

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

# Configuration
PROXMOX_HOST="${PROXMOX_HOST:-192.168.11.11}"
VMID="${VMID_SANKOFA_POSTGRES:-7803}"
CONTAINER_IP="${SANKOFA_POSTGRES_IP:-10.160.0.13}"
DB_NAME="${DB_NAME:-sankofa}"
DB_USER="${DB_USER:-sankofa}"
DB_PASSWORD="${DB_PASSWORD:-$(openssl rand -base64 32 | tr -dc 'a-zA-Z0-9' | cut -c1-24)}"
POSTGRES_VERSION="${POSTGRES_VERSION:-16}"

# SSH function
ssh_r630_01() {
    ssh -o StrictHostKeyChecking=no -o ConnectTimeout=5 root@"$PROXMOX_HOST" "$@"
}

# Execute command in container
exec_container() {
    ssh_r630_01 "pct exec $VMID -- $*"
}

main() {
    echo ""
    log_info "========================================="
    log_info "PostgreSQL Setup for Sankofa"
    log_info "========================================="
    echo ""
    log_info "Container VMID: $VMID"
    log_info "Container IP: $CONTAINER_IP"
    log_info "Database: $DB_NAME"
    log_info "User: $DB_USER"
    echo ""
    
    # Check if container exists and is running
    log_info "Checking container status..."
    if ! ssh_r630_01 "pct status $VMID >/dev/null 2>&1"; then
        log_error "Container $VMID does not exist or is not running"
        exit 1
    fi
    
    # Check if container is running
    local status=$(ssh_r630_01 "pct status $VMID" 2>/dev/null | awk '{print $2}' || echo "stopped")
    if [[ "$status" != "running" ]]; then
        log_info "Starting container $VMID..."
        ssh_r630_01 "pct start $VMID"
        sleep 5
    fi
    log_success "Container is running"
    echo ""
    
    # Install PostgreSQL
    log_info "Installing PostgreSQL $POSTGRES_VERSION..."
    exec_container bash -c "export DEBIAN_FRONTEND=noninteractive && \
        apt-get update -qq && \
        apt-get install -y -qq wget ca-certificates gnupg lsb-release"
    
    exec_container bash -c "wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | apt-key add - && \
        echo 'deb http://apt.postgresql.org/pub/repos/apt \$(lsb_release -cs)-pgdg main' > /etc/apt/sources.list.d/pgdg.list && \
        apt-get update -qq && \
        apt-get install -y -qq postgresql-$POSTGRES_VERSION postgresql-contrib-$POSTGRES_VERSION"
    
    log_success "PostgreSQL installed"
    echo ""
    
    # Configure PostgreSQL
    log_info "Configuring PostgreSQL..."
    exec_container bash -c "systemctl enable postgresql"
    exec_container bash -c "systemctl start postgresql"
    
    # Wait for PostgreSQL to be ready
    log_info "Waiting for PostgreSQL to start..."
    sleep 5
    
    # Create database and user
    log_info "Creating database and user..."
    exec_container bash -c "sudo -u postgres psql << 'EOF'
-- Create user
CREATE USER $DB_USER WITH PASSWORD '$DB_PASSWORD';

-- Create database
CREATE DATABASE $DB_NAME OWNER $DB_USER ENCODING 'UTF8';

-- Grant privileges
GRANT ALL PRIVILEGES ON DATABASE $DB_NAME TO $DB_USER;

-- Connect to database and grant schema privileges
\c $DB_NAME
GRANT ALL ON SCHEMA public TO $DB_USER;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO $DB_USER;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO $DB_USER;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON FUNCTIONS TO $DB_USER;

-- Enable extensions
CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\";
CREATE EXTENSION IF NOT EXISTS \"pg_stat_statements\";
EOF"
    
    log_success "Database and user created"
    echo ""
    
    # Configure PostgreSQL for remote access (if needed)
    log_info "Configuring PostgreSQL for network access..."
    exec_container bash -c "echo \"host    all             all             10.160.0.0/22           md5\" >> /etc/postgresql/$POSTGRES_VERSION/main/pg_hba.conf"
    exec_container bash -c "sed -i \"s/#listen_addresses = 'localhost'/listen_addresses = '*'/\" /etc/postgresql/$POSTGRES_VERSION/main/postgresql.conf"
    
    # Restart PostgreSQL
    exec_container bash -c "systemctl restart postgresql"
    sleep 3
    
    log_success "PostgreSQL configured for network access"
    echo ""
    
    # Test connection
    log_info "Testing database connection..."
    if exec_container bash -c "PGPASSWORD='$DB_PASSWORD' psql -h localhost -U $DB_USER -d $DB_NAME -c 'SELECT version();' >/dev/null 2>&1"; then
        log_success "Database connection successful"
    else
        log_error "Database connection failed"
        exit 1
    fi
    echo ""
    
    # Summary
    log_success "========================================="
    log_success "PostgreSQL Setup Complete"
    log_success "========================================="
    echo ""
    log_info "Database Configuration:"
    echo "  Host: $CONTAINER_IP"
    echo "  Port: 5432"
    echo "  Database: $DB_NAME"
    echo "  User: $DB_USER"
    echo "  Password: $DB_PASSWORD"
    echo ""
    log_info "Next steps:"
    echo "  1. Update .env.r630-01 with the database password"
    echo "  2. Run database migrations: ./scripts/run-migrations-r630-01.sh"
    echo ""
}

main "$@"
