#!/bin/bash

# restore-gitea.sh
# Usage: ./restore-gitea.sh <path_to_backup.tar.gz> <destination_directory>

set -e

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

# Check Arguments
if [ "$#" -ne 2 ]; then
    echo -e "${RED}Usage: $0 <path_to_backup_file> <destination_directory>${NC}"
    echo "Example: $0 ./backups/gitea_backup.tar.gz ~/docker/gitea_restore"
    exit 1
fi

BACKUP_FILE=$(realpath "$1")
DEST_DIR="$2"

# 1. Validation
if [ ! -f "$BACKUP_FILE" ]; then
    echo -e "${RED}Error: Backup file not found at $BACKUP_FILE${NC}"
    exit 1
fi

if [ -d "$DEST_DIR" ]; then
    echo -e "${YELLOW}Warning: Destination directory '$DEST_DIR' already exists.${NC}"
    echo -e "${RED}This process will overwrite files and STOP containers in that directory.${NC}"
    read -p "Are you sure you want to continue? (y/N): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        echo "Restore cancelled."
        exit 1
    fi
else
    echo -e "${BLUE}Creating destination directory: $DEST_DIR${NC}"
    mkdir -p "$DEST_DIR"
fi

# Switch to destination directory
cd "$DEST_DIR" || exit 1

# 2. Extract Backup Archive
echo -e "${BLUE}Step 1/6: Extracting backup archive...${NC}"
tar -xzf "$BACKUP_FILE"
echo "Extraction complete."

# Load environment variables from the extracted .env (if it exists)
if [ -f ".env" ]; then
    echo "Loading .env configuration..."
    export $(grep -v '^#' .env | xargs)
fi

# 3. Stop Existing Services & Clean Volumes
echo -e "${BLUE}Step 2/6: Preparing Docker environment...${NC}"
# We stop containers and remove volumes to ensure a clean restore state
docker compose down -v 2>/dev/null || true
echo "Environment cleaned."

# 4. Restore Volume Data (Files)
echo -e "${BLUE}Step 3/6: Restoring Gitea Data Volume...${NC}"
# We must create the containers (no-start) first so the volume exists
docker compose create gitea

# Helper container to extract data into the volume
docker run --rm \
    --volumes-from gitea \
    -v "$DEST_DIR":/backup \
    alpine tar xzf /backup/gitea_data.tar.gz -C /data

echo "Gitea data restored."

# Restore Runner Data (if present)
if [ -f "runner_data.tar.gz" ]; then
    echo -e "${BLUE}Step 4/6: Restoring Runner Data Volume...${NC}"
    docker compose create runner 2>/dev/null || true
    if docker compose ps -a | grep -q "runner"; then
        docker run --rm \
            --volumes-from gitea-runner \
            -v "$DEST_DIR":/backup \
            alpine tar xzf /backup/runner_data.tar.gz -C /data
        echo "Runner data restored."
    else
         echo -e "${YELLOW}Runner service not defined in compose file. Skipping.${NC}"
    fi
else
    echo "No runner backup found. Skipping."
fi

# 5. Restore Database
echo -e "${BLUE}Step 5/6: Restoring Database...${NC}"
# Start only the DB container
docker compose up -d db

# Wait for Postgres to be ready
echo "Waiting for Database to initialize (15s)..."
sleep 15

if [ -f "database.sql" ]; then
    echo "Importing SQL dump..."
    cat database.sql | docker compose exec -T db psql -U "${POSTGRES_USER:-gitea}" -d "${POSTGRES_DB:-gitea}"
    echo "Database import successful."
else
    echo -e "${RED}Error: database.sql not found in backup!${NC}"
    exit 1
fi

# 6. Start All Services
echo -e "${BLUE}Step 6/6: Starting Gitea...${NC}"
docker compose up -d

# Cleanup extracted files (Optional - comment out if you want to inspect them)
# echo "Cleaning up temporary extraction files..."
# rm database.sql gitea_data.tar.gz runner_data.tar.gz

echo -e "${GREEN}=======================================${NC}"
echo -e "${GREEN}✅ Restore Complete!${NC}"
echo -e "${GREEN}Gitea is running at: $DEST_DIR${NC}"
echo -e "${GREEN}=======================================${NC}"