#!/bin/bash

################################################################################
# Acronis Plan Manager
################################################################################
# Purpose: Manage Acronis protection plans
# Features:
# - List protection plans
# - View plan details
# - Enable/disable plans
# - Guidance for plan configuration
################################################################################

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 "Protection Plan Management"

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 plans
echo -e "${BOLD}Current Protection Plans${NC}"
echo ""

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

if echo "$plan_output" | grep -qi "error\|no.*plans"; then
    echo -e "${YELLOW}No protection plans configured${NC}"
    HAS_PLANS=false
else
    echo "$plan_output"
    HAS_PLANS=true
fi

echo ""
echo -e "${CYAN}──────────────────────────────────────────────────────────────${NC}"
echo ""

if [ "$HAS_PLANS" = true ]; then
    echo -e "${BOLD}Plan Management Options${NC}"
    echo ""
    echo "  1) View detailed plan information"
    echo "  2) Enable/disable plan"
    echo "  3) Delete plan"
    echo "  4) Create new plan (via web console)"
    echo "  0) Return"
    echo ""
    echo -n "Select option [0]: "
    read -r choice
    choice="${choice:-0}"

    case "$choice" in
        1)
            echo ""
            echo -n "Enter plan ID or name: "
            read -r plan_id

            if [ -n "$plan_id" ]; then
                echo ""
                echo -e "${BOLD}Plan Details:${NC}"
                echo ""
                /usr/sbin/acrocmd show plan "$plan_id" 2>&1 || {
                    echo ""
                    print_error "Could not retrieve plan details"
                    echo "Check that the plan ID/name is correct"
                }
            fi
            ;;

        2)
            echo ""
            echo -n "Enter plan ID to enable/disable: "
            read -r plan_id

            if [ -n "$plan_id" ]; then
                echo ""
                echo "  1) Enable plan"
                echo "  2) Disable plan"
                echo ""
                echo -n "Select [1]: "
                read -r action
                action="${action:-1}"

                if [ "$action" = "1" ]; then
                    /usr/sbin/acrocmd plan enable "$plan_id" 2>&1 && {
                        print_success "Plan enabled"
                    } || {
                        print_error "Failed to enable plan"
                    }
                else
                    /usr/sbin/acrocmd plan disable "$plan_id" 2>&1 && {
                        print_success "Plan disabled"
                    } || {
                        print_error "Failed to disable plan"
                    }
                fi
            fi
            ;;

        3)
            echo ""
            echo -e "${RED}${BOLD}Delete Protection Plan${NC}"
            echo ""
            echo -e "${YELLOW}Warning:${NC} This will delete the plan configuration."
            echo "Existing backups will be retained."
            echo ""
            echo -n "Enter plan ID to delete: "
            read -r plan_id

            if [ -n "$plan_id" ]; then
                echo ""
                echo -n "Confirm deletion (type 'yes'): "
                read -r confirm

                if [ "$confirm" = "yes" ]; then
                    /usr/sbin/acrocmd delete plan "$plan_id" 2>&1 && {
                        print_success "Plan deleted"
                    } || {
                        print_error "Failed to delete plan"
                    }
                else
                    echo "Cancelled"
                fi
            fi
            ;;

        4)
            echo ""
            echo -e "${BOLD}Create New Protection Plan${NC}"
            echo ""
            echo "Protection plans are best created via the web console"
            echo "for full configuration options and validation."
            echo ""
            echo -e "${CYAN}Web Console Method:${NC}"
            echo ""
            echo "1. Log in to Acronis web console"

            # 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 → Select this server"
            echo "3. Click 'Add protection plan'"
            echo "4. Configure plan settings:"
            echo "   • What to back up (entire system/volumes/files)"
            echo "   • Where to store (cloud/local)"
            echo "   • When to run (schedule)"
            echo "   • How long to keep (retention)"
            echo "5. Save and activate"
            echo ""
            echo -e "${BOLD}Advanced CLI Method:${NC}"
            echo ""
            echo "For advanced users, plans can be created via acrocmd:"
            echo "  acrocmd create plan --help"
            ;;
    esac
else
    echo -e "${BOLD}Getting Started with Protection Plans${NC}"
    echo ""
    echo "Protection plans define your backup strategy:"
    echo ""
    echo -e "${CYAN}What:${NC}  Files, folders, volumes, or entire system"
    echo -e "${CYAN}Where:${NC} Cloud storage or local destination"
    echo -e "${CYAN}When:${NC}  Scheduled times (hourly/daily/weekly/monthly)"
    echo -e "${CYAN}Keep:${NC}  Retention policy (days/versions to keep)"
    echo ""
    echo -e "${BOLD}To Create Your First Plan:${NC}"
    echo ""
    echo "1. Log in to Acronis web console"

    # 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 'Add protection plan'"
    echo "4. Follow the configuration wizard"
    echo "5. Activate the plan"
    echo ""
    echo -e "${GREEN}Tip:${NC} Start with a simple file backup plan to test,"
    echo "     then create full system backup plans as needed."
fi

echo ""
press_enter
