#!/bin/bash
# Full Server Restore Script for V2-Docker
# Restores server from a backup created by create_full_backup.sh

set -e  # Exit on error

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

# Check if backup path is provided
if [ $# -eq 0 ]; then
    echo -e "${RED}Error: No backup specified${NC}"
    echo "Usage: $0 <backup_path_or_name>"
    echo ""
    echo "Examples:"
    echo "  $0 server_backup_20250628_171705"
    echo "  $0 /opt/v2-Docker/server-backups/server_backup_20250628_171705"
    echo "  $0 server_backup_20250628_171705.tar.gz"
    exit 1
fi

BACKUP_INPUT="$1"
PROJECT_ROOT="/opt/v2-Docker"
BACKUP_BASE_DIR="$PROJECT_ROOT/server-backups"

# Determine backup directory
if [ -d "$BACKUP_INPUT" ]; then
    # Full path provided
    BACKUP_DIR="$BACKUP_INPUT"
elif [ -d "$BACKUP_BASE_DIR/$BACKUP_INPUT" ]; then
    # Backup name provided
    BACKUP_DIR="$BACKUP_BASE_DIR/$BACKUP_INPUT"
elif [ -f "$BACKUP_BASE_DIR/$BACKUP_INPUT" ] && [[ "$BACKUP_INPUT" == *.tar.gz ]]; then
    # Tar file provided - extract first
    echo -e "${YELLOW}Extracting backup archive...${NC}"
    TEMP_DIR=$(mktemp -d)
    tar xzf "$BACKUP_BASE_DIR/$BACKUP_INPUT" -C "$TEMP_DIR"
    BACKUP_DIR=$(find "$TEMP_DIR" -maxdepth 1 -type d -name "server_backup_*" | head -1)
    if [ -z "$BACKUP_DIR" ]; then
        echo -e "${RED}Error: Could not find backup directory in archive${NC}"
        rm -rf "$TEMP_DIR"
        exit 1
    fi
else
    echo -e "${RED}Error: Backup not found: $BACKUP_INPUT${NC}"
    exit 1
fi

echo -e "${GREEN}Starting V2-Docker Full Server Restore...${NC}"
echo "Restoring from: $BACKUP_DIR"

# Verify backup directory structure
if [ ! -f "$BACKUP_DIR/database_backup.sql.gz" ]; then
    echo -e "${RED}Error: Invalid backup - database_backup.sql.gz not found${NC}"
    exit 1
fi

# Warning prompt
echo -e "${YELLOW}WARNING: This will restore the entire server state!${NC}"
echo "This includes:"
echo "  - Configuration files"
echo "  - SSL certificates"
echo "  - Database (all data will be replaced)"
echo "  - Docker volumes"
echo ""
read -p "Are you sure you want to continue? (yes/no): " CONFIRM

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

# 1. Stop all services
echo -e "${YELLOW}Stopping Docker services...${NC}"
cd "$PROJECT_ROOT"
docker-compose down

# 2. Restore configuration files
echo -e "${YELLOW}Restoring configuration files...${NC}"
if [ -f "$BACKUP_DIR/configs/docker-compose.yaml" ]; then
    cp "$BACKUP_DIR/configs/docker-compose.yaml" "$PROJECT_ROOT/"
fi
if [ -f "$BACKUP_DIR/configs/.env" ]; then
    cp "$BACKUP_DIR/configs/.env" "$PROJECT_ROOT/"
fi
if [ -f "$BACKUP_DIR/configs/nginx.conf" ]; then
    mkdir -p "$PROJECT_ROOT/v2_nginx"
    cp "$BACKUP_DIR/configs/nginx.conf" "$PROJECT_ROOT/v2_nginx/"
fi

# Restore SSL certificates
if [ -d "$BACKUP_DIR/configs/ssl" ]; then
    mkdir -p "$PROJECT_ROOT/v2_nginx/ssl"
    cp -r "$BACKUP_DIR/configs/ssl/"* "$PROJECT_ROOT/v2_nginx/ssl/"
fi

# 3. Restore Docker volumes
echo -e "${YELLOW}Restoring Docker volumes...${NC}"
# Remove old volume
docker volume rm v2_postgres_data 2>/dev/null || true
# Create new volume
docker volume create v2_postgres_data
# Restore volume data
docker run --rm -v v2_postgres_data:/data -v "$BACKUP_DIR/volumes":/backup alpine tar xzf /backup/v2_postgres_data.tar.gz -C /data

# 4. Start database service only
echo -e "${YELLOW}Starting database service...${NC}"
docker-compose up -d db

# Wait for database to be ready
echo "Waiting for database to be ready..."
sleep 10

# 5. Restore database
echo -e "${YELLOW}Restoring database...${NC}"
DB_CONTAINER="v2_postgres"
DB_NAME="v2_license_db"
DB_USER="v2_user"

# Get DB password from restored .env
if [ -f "$PROJECT_ROOT/.env" ]; then
    source "$PROJECT_ROOT/.env"
fi
DB_PASS="${POSTGRES_PASSWORD:-${DB_PASS:-v2_password}}"

# Drop and recreate database
docker exec "$DB_CONTAINER" psql -U "$DB_USER" -c "DROP DATABASE IF EXISTS $DB_NAME;"
docker exec "$DB_CONTAINER" psql -U "$DB_USER" -c "CREATE DATABASE $DB_NAME;"

# Restore database from backup
gunzip -c "$BACKUP_DIR/database_backup.sql.gz" | docker exec -i "$DB_CONTAINER" psql -U "$DB_USER" -d "$DB_NAME"

# 6. Start all services
echo -e "${YELLOW}Starting all services...${NC}"
docker-compose up -d

# Wait for services to be ready
echo "Waiting for services to start..."
sleep 15

# 7. Verify services are running
echo -e "${YELLOW}Verifying services...${NC}"
docker-compose ps

# Clean up temporary directory if used
if [ -n "$TEMP_DIR" ] && [ -d "$TEMP_DIR" ]; then
    rm -rf "$TEMP_DIR"
fi

echo -e "${GREEN}Restore completed successfully!${NC}"
echo ""
echo "Next steps:"
echo "1. Verify the application is working at https://admin-panel-undso.intelsight.de"
echo "2. Check logs: docker-compose logs -f"
echo "3. If there are issues, check the backup info: cat $BACKUP_DIR/backup_info.txt"