#!/bin/bash

# Configuration
BACKUP_DIR="/backups"
DB_HOST="mold_cost_db"
DB_NAME="mold_cost"
DB_USER="postgres"
DB_PASSWORD="postgres"

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

# Function to list available backups
list_backups() {
    echo "Available backups:"
    ls -la "$BACKUP_DIR"/backup_*.sql.gz 2>/dev/null | while read -r line; do
        echo "  $line"
    done
}

# Function to restore from backup
restore_backup() {
    local backup_file="$1"
    
    if [ ! -f "$backup_file" ]; then
        echo "ERROR: Backup file '$backup_file' not found!"
        list_backups
        exit 1
    fi
    
    echo "WARNING: This will overwrite the current database!"
    echo "Backup file: $backup_file"
    read -p "Are you sure you want to continue? (y/N): " -n 1 -r
    echo
    
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        echo "Restoring database from backup..."
        
        # Drop and recreate database
        echo "Dropping existing database..."
        dropdb -h "$DB_HOST" -U "$DB_USER" --no-password "$DB_NAME" 2>/dev/null || true
        
        echo "Creating new database..."
        createdb -h "$DB_HOST" -U "$DB_USER" --no-password "$DB_NAME"
        
        echo "Restoring data..."
        if gunzip -c "$backup_file" | psql -h "$DB_HOST" -U "$DB_USER" -d "$DB_NAME" --no-password; then
            echo "Database restored successfully!"
        else
            echo "ERROR: Database restore failed!"
            exit 1
        fi
    else
        echo "Restore cancelled."
    fi
}

# Main script logic
if [ $# -eq 0 ]; then
    echo "Usage: $0 [list|restore <backup_file>]"
    echo ""
    echo "Commands:"
    echo "  list                    - List available backups"
    echo "  restore <backup_file>   - Restore database from backup file"
    echo ""
    echo "Examples:"
    echo "  $0 list"
    echo "  $0 restore /backups/backup_20241201_120000.sql.gz"
    exit 1
fi

case "$1" in
    "list")
        list_backups
        ;;
    "restore")
        if [ -z "$2" ]; then
            echo "ERROR: Please specify a backup file to restore from."
            echo "Usage: $0 restore <backup_file>"
            exit 1
        fi
        restore_backup "$2"
        ;;
    *)
        echo "ERROR: Unknown command '$1'"
        echo "Usage: $0 [list|restore <backup_file>]"
        exit 1
        ;;
esac

# Clear password from environment
unset PGPASSWORD 