#!/bin/bash

# Configuration
DEV_DB_HOST="db"
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"

# Create backup directory if it doesn't exist
BACKUP_DIR="./db_backups"
mkdir -p "$BACKUP_DIR"

# Get current date for backup file name
DATE=$(date +"%Y%m%d_%H%M%S")

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

# Function to create backup
create_backup() {
    local env=$1
    local host=$2
    local port=$3
    local db=$4
    local user=$5
    local password=$6

    # Set backup filename
    local backup_file="${BACKUP_DIR}/eveai_${env}_backup_${DATE}.sql"

    echo "Creating backup for ${env} environment..."
    echo "Backing up to: ${backup_file}"

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

    # Create backup using pg_dump
    pg_dump -h "$host" -p "$port" -U "$user" -d "$db" -F p > "$backup_file"

    # Check if backup was successful
    if [ $? -eq 0 ]; then
        echo "Backup completed successfully!"
        echo "Backup file: ${backup_file}"

        # Create compressed version
        gzip -f "$backup_file"
        echo "Compressed backup created: ${backup_file}.gz"
    else
        echo "Error: Backup failed!"
        rm -f "$backup_file" # Clean up failed backup file
        exit 1
    fi

    # Unset PGPASSWORD for security
    unset PGPASSWORD
}

# Function to display usage
usage() {
    echo "Usage: $0 [dev|prod]"
    echo "  dev  - backup development database"
    echo "  prod - backup production database"
    exit 1
}

# Main script logic
main() {
    # Check for pg_dump
    check_pg_dump

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

    case "$1" in
        "dev")
            create_backup "dev" "$DEV_DB_HOST" "$DEV_DB_PORT" "$DEV_DB_NAME" "$DEV_DB_USER" "$DEV_DB_PASSWORD"
            ;;
        "prod")
            create_backup "prod" "$PROD_DB_HOST" "$PROD_DB_PORT" "$PROD_DB_NAME" "$PROD_DB_USER" "$PROD_DB_PASSWORD"
            ;;
        *)
            usage
            ;;
    esac
}

# Run main function
main "$@"