#!/bin/bash

# Configuration
DEV_DB_HOST="localhost"
DEV_DB_PORT="5432"
DEV_DB_NAME="eveai"
DEV_DB_USER="luke"
DEV_DB_PASSWORD="Skywalker!"

PROD_DB_HOST="bswnz4.stackhero-network.com"
PROD_DB_PORT="5945"
PROD_DB_NAME="eveai"
PROD_DB_USER="luke_skywalker"
PROD_DB_PASSWORD="2MK&1rHmWEydE2rFuJLq*ls%tdkPAk2"

# Backup directory
BACKUP_DIR="./db_backups"

# Function to check if psql is available
check_psql() {
    if ! command -v psql &> /dev/null; then
        echo "Error: psql is not installed. Please install PostgreSQL client tools."
        exit 1
    fi
}

# Function to list available backups
list_backups() {
    echo "Available backups:"
    ls -lh "${BACKUP_DIR}"/*.gz 2>/dev/null || echo "No backups found in ${BACKUP_DIR}"
}

# Function to restore backup
restore_backup() {
    local env=$1
    local backup_file=$2
    local host=""
    local port=""
    local db=""
    local user=""
    local password=""

    # Set environment-specific variables
    case "$env" in
        "dev")
            host="$DEV_DB_HOST"
            port="$DEV_DB_PORT"
            db="$DEV_DB_NAME"
            user="$DEV_DB_USER"
            password="$DEV_DB_PASSWORD"
            ;;
        "prod")
            host="$PROD_DB_HOST"
            port="$PROD_DB_PORT"
            db="$PROD_DB_NAME"
            user="$PROD_DB_USER"
            password="$PROD_DB_PASSWORD"
            ;;
        *)
            echo "Invalid environment specified"
            exit 1
            ;;
    esac

    # Check if backup file exists
    if [ ! -f "$backup_file" ]; then
        echo "Error: Backup file not found: $backup_file"
        exit 1
    fi

    # Safety confirmation
    echo "WARNING: This will overwrite the current $env database!"
    echo "Database: $db"
    echo "Host: $host"
    echo "Port: $port"
    read -p "Are you sure you want to proceed? (type 'yes' to confirm): " confirm
    if [ "$confirm" != "yes" ]; then
        echo "Restore cancelled."
        exit 1
    fi

    echo "Starting restore process..."

    # Create temporary directory for uncompressed backup
    local temp_dir=$(mktemp -d)
    local temp_file="${temp_dir}/temp_backup.sql"

    # Uncompress backup file
    echo "Uncompressing backup file..."
    gunzip -c "$backup_file" > "$temp_file"

    # Set PGPASSWORD environment variable
    export PGPASSWORD="$password"

    # Terminate existing connections
    echo "Terminating existing database connections..."
    psql -h "$host" -p "$port" -U "$user" -d "postgres" -c "
        SELECT pg_terminate_backend(pid)
        FROM pg_stat_activity
        WHERE datname = '$db'
        AND pid <> pg_backend_pid();" >/dev/null 2>&1

    # Drop and recreate database
    echo "Dropping and recreating database..."
    psql -h "$host" -p "$port" -U "$user" -d "postgres" -c "DROP DATABASE IF EXISTS $db WITH (FORCE);"
    psql -h "$host" -p "$port" -U "$user" -d "postgres" -c "CREATE DATABASE $db;"

    # Restore backup
    echo "Restoring backup..."
    psql -h "$host" -p "$port" -U "$user" -d "$db" < "$temp_file"

    # Check if restore was successful
    if [ $? -eq 0 ]; then
        echo "Restore completed successfully!"
    else
        echo "Error: Restore failed!"
        # Clean up
        rm -rf "$temp_dir"
        unset PGPASSWORD
        exit 1
    fi

    # Clean up
    rm -rf "$temp_dir"
    unset PGPASSWORD
}

# Function to display usage
usage() {
    echo "Usage: $0 [dev|prod] [backup_file|list]"
    echo "  dev <backup_file>  - restore development database from backup file"
    echo "  prod <backup_file> - restore production database from backup file"
    echo "  list              - list available backup files"
    echo ""
    echo "Example:"
    echo "  $0 dev ./db_backups/eveai_dev_backup_20250116_123456.sql.gz"
    exit 1
}

# Main script logic
main() {
    # Check for psql
    check_psql

    # Check command line arguments
    if [ $# -lt 1 ]; then
        usage
    fi

    # Handle list command
    if [ "$1" = "list" ]; then
        list_backups
        exit 0
    fi

    # Check for required arguments
    if [ $# -ne 2 ]; then
        usage
    fi

    # Handle restore commands
    case "$1" in
        "dev"|"prod")
            restore_backup "$1" "$2"
            ;;
        *)
            usage
            ;;
    esac
}

# Run main function
main "$@"