#!/bin/bash

################################################################################
# Acronis Trigger Backup
################################################################################
# Purpose: Trigger manual backups using acrocmd
# Features:
# - List available backup plans
# - Run backup for specific plan
# - Trigger ad-hoc backup
################################################################################

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
source "$SCRIPT_DIR/lib/common-functions.sh"
source "$SCRIPT_DIR/lib/system-detect.sh"

if [ "$EUID" -ne 0 ]; then
    print_error "This script must be run as root"
    exit 1
fi

clear
print_banner "Trigger Manual Backup"

echo ""

# Check if acrocmd is available
if [ ! -f "/usr/sbin/acrocmd" ]; then
    print_error "acrocmd command-line tool not found"
    echo ""
    press_enter
    exit 1
fi

# List available plans
echo -e "${BOLD}Available Backup Plans${NC}"
echo ""
echo "Querying backup plans from Acronis..."
echo ""

plan_output=$(/usr/sbin/acrocmd list plans 2>&1)

# Check if no plans exist (empty output or success message only)
if echo "$plan_output" | grep -qi "error\|failed\|no plans" || ! echo "$plan_output" | grep -q "[a-f0-9]\{8\}-[a-f0-9]\{4\}"; then
    echo -e "${YELLOW}No backup plans found or error querying plans${NC}"
    echo ""
    echo "Possible reasons:"
    echo "  • No CLI-managed plans exist (acrocmd only shows local plans)"
    echo "  • Cloud-managed plans created in web console are not visible here"
    echo "  • Agent not registered with Acronis Cloud"
    echo ""
    echo -e "${CYAN}──────────────────────────────────────────────────────────────${NC}"
    echo ""
    echo -e "${BOLD}Important Note:${NC}"
    echo ""
    echo "Plans created in the Acronis web console are managed at the cloud level"
    echo "and are NOT accessible via the acrocmd CLI tool. The CLI can only see and"
    echo "manage plans created locally via acrocmd commands."
    echo ""
    echo -e "${BOLD}To Trigger Cloud-Managed Backups:${NC}"
    echo ""
    echo "1. Log in to Acronis web console"
    echo "2. Navigate to: Devices → Select this server"
    echo "3. Click 'Back up now' to trigger your existing plan"
    echo ""
    echo -e "${BOLD}To Create CLI-Managed Plans:${NC}"
    echo ""
    echo "Use: acrocmd create plan --help"
    echo "Note: CLI plans give you more control and optimization options"
    echo ""
    press_enter
    exit 0
fi

echo "$plan_output"
echo ""
echo -e "${CYAN}──────────────────────────────────────────────────────────────${NC}"
echo ""
echo -e "${BOLD}Select a Plan to Backup:${NC}"
echo ""
echo "Enter the plan name or ID from the list above,"
echo "or press Enter to cancel and use web console instead."
echo ""
echo -n "Plan name/ID: "
read -r plan_id

if [ -z "$plan_id" ]; then
    echo ""
    echo -e "${BOLD}Use Web Console Instead${NC}"
    echo ""
    echo "To trigger backup via web console:"
    echo ""
    echo "1. Log in to Acronis web console"

    # Try to get cloud URL
    if [ -f "/etc/Acronis/Global.config" ]; then
        cloud_url=$(grep -oP 'CloudUrl[>=\"].*?https://[^\"<]+' /etc/Acronis/Global.config 2>/dev/null | grep -oP 'https://[^\"<]+' | head -1)
        if [ -n "$cloud_url" ]; then
            echo "   ${cloud_url}"
        fi
    fi

    echo ""
    echo "2. Navigate to: Devices → This server"
    echo "3. Click 'Back up now' button"
    echo "4. Monitor progress in real-time"
    echo ""
    press_enter
    exit 0
fi

# User selected a plan, proceed with backup type selection
echo ""
echo -e "${BOLD}Backup Type Selection${NC}"
        echo ""
        echo "Select backup type:"
        echo "  1) Auto (use plan's configured type)"
        echo "  2) Full backup"
        echo "  3) Incremental backup"
        echo "  4) Differential backup"
        echo ""
        echo -n "Select type [1]: "
        read -r backup_type_choice
        backup_type_choice="${backup_type_choice:-1}"

        BACKUP_FLAGS=""
        case "$backup_type_choice" in
            2)
                BACKUP_FLAGS="--backuptype=full"
                echo "  → Full backup selected"
                ;;
            3)
                BACKUP_FLAGS="--backuptype=incremental"
                echo "  → Incremental backup selected (faster, stores only changes)"
                ;;
            4)
                BACKUP_FLAGS="--backuptype=differential"
                echo "  → Differential backup selected (changes since last full)"
                ;;
            *)
                echo "  → Using plan's default backup type"
                ;;
        esac

        echo ""
        echo -e "${BOLD}Performance Options${NC}"
        echo ""
        echo -n "Enable performance optimizations? (y/n) [n]: "
        read -r opt_choice

        if [ "$opt_choice" = "y" ] || [ "$opt_choice" = "Y" ]; then
            echo ""
            echo "Available optimizations:"
            echo "  1) Lower compression (faster backup, larger size)"
            echo "  2) High priority (use more system resources)"
            echo "  3) Both"
            echo ""
            echo -n "Select [3]: "
            read -r perf_choice
            perf_choice="${perf_choice:-3}"

            case "$perf_choice" in
                1)
                    BACKUP_FLAGS="$BACKUP_FLAGS --compression=normal"
                    echo "  → Lower compression enabled"
                    ;;
                2)
                    BACKUP_FLAGS="$BACKUP_FLAGS --priority=high"
                    echo "  → High priority enabled"
                    ;;
                3)
                    BACKUP_FLAGS="$BACKUP_FLAGS --compression=normal --priority=high"
                    echo "  → Lower compression + high priority enabled"
                    ;;
            esac
        fi

        echo ""
        echo -e "${BOLD}Starting Backup...${NC}"
        echo ""
        echo "Plan: $plan_id"
        [ -n "$BACKUP_FLAGS" ] && echo "Options: $BACKUP_FLAGS"
        echo ""

        # Try to run backup
        if /usr/sbin/acrocmd backup run --plan "$plan_id" $BACKUP_FLAGS 2>&1; then
            echo ""
            print_success "Backup initiated successfully"
            echo ""
            echo "Monitor progress with 'Check Backup Status'"
        else
            echo ""
            print_error "Failed to start backup"
            echo ""
            echo "Check that:"
            echo "  • Plan ID/name is correct"
            echo "  • Agent is online and registered"
            echo "  • No conflicting backups running"
        fi

echo ""
press_enter
