#!/bin/bash
# GuruConnect PostgreSQL Restore Script
# Restores a GuruConnect database backup

set -e

# Configuration
DB_NAME="guruconnect"
DB_USER="guruconnect"
DB_HOST="localhost"

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

# Check arguments
if [ $# -eq 0 ]; then
    echo -e "${RED}ERROR: No backup file specified${NC}"
    echo ""
    echo "Usage: $0 <backup-file.sql.gz>"
    echo ""
    echo "Example:"
    echo "  $0 /home/guru/backups/guruconnect/guruconnect-2026-01-18-020000.sql.gz"
    echo ""
    echo "Available backups:"
    ls -lh /home/guru/backups/guruconnect/*.sql.gz 2>/dev/null || echo "  No backups found"
    exit 1
fi

BACKUP_FILE="$1"

# Check if backup file exists
if [ ! -f "$BACKUP_FILE" ]; then
    echo -e "${RED}ERROR: Backup file not found: $BACKUP_FILE${NC}"
    exit 1
fi

echo "========================================="
echo "GuruConnect Database Restore"
echo "========================================="
echo "Date: $(date)"
echo "Database: $DB_NAME"
echo "Backup file: $BACKUP_FILE"
echo ""

# Warning
echo -e "${YELLOW}WARNING: This will OVERWRITE the current database!${NC}"
echo ""
read -p "Are you sure you want to restore? (yes/no): " -r
echo
if [[ ! $REPLY =~ ^[Yy][Ee][Ss]$ ]]; then
    echo "Restore cancelled."
    exit 0
fi

# Stop GuruConnect server (if running as systemd service)
echo "Stopping GuruConnect server..."
if systemctl is-active --quiet guruconnect 2>/dev/null; then
    sudo systemctl stop guruconnect
    echo -e "${GREEN}Server stopped${NC}"
else
    echo "Server not running or not managed by systemd"
fi

# Drop and recreate database
echo ""
echo "Dropping existing database..."
PGPASSWORD="${DB_PASSWORD:-}" psql -h "$DB_HOST" -U "$DB_USER" -c "DROP DATABASE IF EXISTS $DB_NAME;" postgres

echo "Creating new database..."
PGPASSWORD="${DB_PASSWORD:-}" psql -h "$DB_HOST" -U "$DB_USER" -c "CREATE DATABASE $DB_NAME;" postgres

# Restore backup
echo ""
echo "Restoring from backup..."
if gunzip -c "$BACKUP_FILE" | PGPASSWORD="${DB_PASSWORD:-}" psql -h "$DB_HOST" -U "$DB_USER" "$DB_NAME"; then
    echo -e "${GREEN}SUCCESS: Database restored${NC}"
else
    echo -e "${RED}ERROR: Restore failed${NC}"
    exit 1
fi

# Restart GuruConnect server
echo ""
echo "Starting GuruConnect server..."
if systemctl is-enabled --quiet guruconnect 2>/dev/null; then
    sudo systemctl start guruconnect
    sleep 2
    if systemctl is-active --quiet guruconnect; then
        echo -e "${GREEN}Server started successfully${NC}"
    else
        echo -e "${RED}ERROR: Server failed to start${NC}"
        echo "Check logs with: sudo journalctl -u guruconnect -n 50"
    fi
else
    echo "Server not configured as systemd service - start manually"
fi

echo ""
echo "========================================="
echo "Restore completed!"
echo "========================================="
