#!/bin/bash
# restore.sh - Restore PostgreSQL database from backup
# Run this as user 'press-api' with backup filename as argument
# Uses podman-compose to manage containerized services

set -e

COMPOSE_FILE="$HOME/Press.Zone-Works/press-zone-backend/podman-compose.yml"

if [ $# -eq 0 ]; then
    echo "Usage: $0 <backup_file>"
    echo ""
    echo "Available backups:"
    ls -lh "$HOME/press-zone-backend/backup" | grep postgres
    exit 1
fi

BACKUP_FILE="$1"
DB_USER="translate_user"
DB_NAME="translate_db"

if [ ! -f "$BACKUP_FILE" ]; then
    echo "ERROR: Backup file not found: $BACKUP_FILE"
    exit 1
fi

echo "WARNING: This will restore database '$DB_NAME' from backup."
echo "Current data will be OVERWRITTEN!"
echo ""
read -p "Are you sure? (type 'yes' to continue): " confirm

if [ "$confirm" != "yes" ]; then
    echo "Restore cancelled."
    exit 0
fi

# Stop API and Worker containers (keep postgres running)
echo "Stopping API and Worker containers..."
podman-compose -f "$COMPOSE_FILE" stop api worker

# Decompress if needed and pipe into containerized pg_restore
echo "Restoring database from backup..."
if [[ "$BACKUP_FILE" == *.gz ]]; then
    gunzip -c "$BACKUP_FILE" | podman exec -i tpz-postgres pg_restore -U "$DB_USER" -d "$DB_NAME" -F c --clean --if-exists || {
        echo "ERROR: Database restore failed"
        podman-compose -f "$COMPOSE_FILE" up -d api worker
        exit 1
    }
else
    podman exec -i tpz-postgres pg_restore -U "$DB_USER" -d "$DB_NAME" -F c --clean --if-exists < "$BACKUP_FILE" || {
        echo "ERROR: Database restore failed"
        podman-compose -f "$COMPOSE_FILE" up -d api worker
        exit 1
    }
fi

# Restart API and Worker containers
echo "Starting API and Worker containers..."
podman-compose -f "$COMPOSE_FILE" up -d api worker

echo "Database restored successfully!"
echo "Waiting for services to start..."
sleep 10

# Health check
if curl -f http://localhost:3000/health > /dev/null 2>&1; then
    echo "Services are running correctly"
else
    echo "WARNING: Health check failed, please check service logs"
    podman-compose -f "$COMPOSE_FILE" logs --tail 20 api
fi
