#!/bin/bash

################################################################################
# Acronis Agent Update/Upgrade
################################################################################
# Purpose: Update Acronis Cyber Protect agent to latest version
# Methods:
# - Automatic via cloud (web console)
# - Manual download and upgrade (preserves config/registration)
################################################################################

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

print_banner "Update Acronis Agent"

echo ""

# Check if Acronis is installed
if ! systemctl list-unit-files | grep -q "acronis_mms.service"; then
    print_error "Acronis is not installed"
    echo ""
    echo "Install Acronis first:"
    echo "  1. Return to Acronis menu"
    echo "  2. Select 'Install Acronis Agent'"
    echo ""
    press_enter
    exit 1
fi

echo -e "${BOLD}Current Installation${NC}"
echo ""

# Check current version
echo "→ Checking current agent version..."
if [ -f "/usr/lib/Acronis/BackupAndRecovery/aakore" ]; then
    current_version=$(/usr/lib/Acronis/BackupAndRecovery/aakore --version 2>/dev/null | head -1 || echo "Unknown")
    echo "  Current version: ${current_version}"
else
    echo "  ${YELLOW}Version unknown${NC}"
fi

# Check service status
echo ""
echo "→ Service status:"
if systemctl is-active --quiet acronis_mms; then
    echo "  ${GREEN}✓${NC} Services are running"
else
    echo "  ${YELLOW}⚠${NC} Some services are stopped"
fi

echo ""
echo -e "${CYAN}──────────────────────────────────────────────────────────────${NC}"
echo ""
echo -e "${BOLD}Update Methods${NC}"
echo ""
echo -e "${CYAN}1. Automatic Update (via Acronis Cloud)${NC}"
echo "   • Managed from web console"
echo "   • Navigate to: Settings → Agent updates"
echo "   • Can enable automatic updates"
echo "   • Recommended for production environments"
echo ""
echo -e "${CYAN}2. Manual Update (Download + Upgrade)${NC}"
echo "   • Downloads latest installer"
echo "   • Runs upgrade automatically"
echo "   • Preserves configuration and registration"
echo "   • Agent stays registered to same account"
echo ""
echo -n "Select update method (1/2) or 0 to cancel [2]: "
read -r method
method="${method:-2}"

case "$method" in
    1)
        # Automatic update instructions
        clear
        print_banner "Automatic Agent Updates"
        echo ""
        echo -e "${BOLD}Configure Automatic Updates via Web Console${NC}"
        echo ""
        echo "Steps:"
        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: Settings → Agent updates"
        echo ""
        echo "  3. Options available:"
        echo "     • Enable automatic updates"
        echo "     • Schedule update time"
        echo "     • Set update policy per device"
        echo "     • Configure notification preferences"
        echo ""
        echo "  4. Agents will update during maintenance window"
        echo ""
        echo -e "${GREEN}Benefits:${NC}"
        echo "  ✓ Centrally managed"
        echo "  ✓ Scheduled updates"
        echo "  ✓ Rollback capability"
        echo "  ✓ Update verification"
        echo ""
        press_enter
        ;;

    2)
        # Manual update/upgrade
        clear
        print_banner "Manual Agent Upgrade"
        echo ""
        echo -e "${BOLD}Upgrade Process${NC}"
        echo ""
        echo "This will:"
        echo "  1. Download the latest Acronis agent installer"
        echo "  2. Run installer over existing installation"
        echo "  3. Automatically upgrade to latest version"
        echo "  4. Preserve all configuration and registration"
        echo "  5. Restart services with new version"
        echo ""
        echo -e "${YELLOW}Note:${NC} The agent will stay registered to your Acronis account."
        echo "       No need to re-register after upgrade."
        echo ""
        echo -e "${CYAN}──────────────────────────────────────────────────────────────${NC}"
        echo ""

        # Get cloud URL for download
        SERVICE_URL="us5-cloud.acronis.com"
        if [ -f "/etc/Acronis/Global.config" ]; then
            config_url=$(grep -oP 'CloudUrl[>="].*?https://[^"<]+' /etc/Acronis/Global.config 2>/dev/null | grep -oP 'https://[^"<]+' | head -1)
            if [ -n "$config_url" ]; then
                SERVICE_URL=$(echo "$config_url" | sed 's|https://||' | sed 's|/.*||')
            fi
        fi

        echo "Download region: ${SERVICE_URL}"
        echo ""
        echo -n "Proceed with upgrade? (yes/no): "
        read -r confirm

        if [[ ! "$confirm" =~ ^[Yy]([Ee][Ss])?$ ]]; then
            echo ""
            print_error "Upgrade cancelled"
            press_enter
            exit 0
        fi

        echo ""
        echo -e "${BOLD}Starting Upgrade...${NC}"
        echo ""

        # Create download directory
        DOWNLOAD_DIR="$SCRIPT_DIR/downloads"
        mkdir -p "$DOWNLOAD_DIR"
        cd "$DOWNLOAD_DIR" || exit 1

        INSTALL_DIR="$DOWNLOAD_DIR/acronis-upgrade-$(date +%Y%m%d-%H%M%S)"
        mkdir -p "$INSTALL_DIR"
        cd "$INSTALL_DIR" || exit 1

        # Download installer
        echo "→ Downloading latest Acronis agent..."
        DOWNLOAD_URL="https://${SERVICE_URL}/bc/api/ams/links/agents/redirect?language=multi&system=linux&architecture=64&productType=enterprise"

        if wget -q --show-progress "$DOWNLOAD_URL" -O "Cyber_Protection_Agent_for_Linux_x86_64.bin"; then
            print_success "Download complete"
        else
            print_error "Download failed"
            echo ""
            echo "Possible causes:"
            echo "  • No internet connection"
            echo "  • Invalid service URL"
            echo "  • Firewall blocking connection"
            echo ""
            cd "$SCRIPT_DIR"
            rm -rf "$INSTALL_DIR"
            press_enter
            exit 1
        fi

        echo ""

        # Make executable
        chmod +x "Cyber_Protection_Agent_for_Linux_x86_64.bin" 2>/dev/null

        # Verify file
        file_size=$(stat -c%s "Cyber_Protection_Agent_for_Linux_x86_64.bin" 2>/dev/null || echo "0")
        if [ "$file_size" -lt 1000000 ]; then
            print_error "Downloaded file is too small (possibly corrupted)"
            cd "$SCRIPT_DIR"
            rm -rf "$INSTALL_DIR"
            press_enter
            exit 1
        fi

        # Run upgrade (unattended mode)
        echo "→ Running upgrade..."
        echo ""
        echo "The installer will automatically:"
        echo "  • Detect existing installation"
        echo "  • Upgrade to latest version"
        echo "  • Preserve configuration"
        echo "  • Keep registration"
        echo ""
        sleep 2

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

        # Run installer in unattended mode
        ./Cyber_Protection_Agent_for_Linux_x86_64.bin -a

        UPGRADE_EXIT_CODE=$?

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

        # Check result
        if [ "${UPGRADE_EXIT_CODE:-0}" -eq 0 ]; then
            print_success "Upgrade completed successfully!"
            echo ""

            # Check new version
            echo "→ Verifying upgrade..."
            sleep 2

            if [ -f "/usr/lib/Acronis/BackupAndRecovery/aakore" ]; then
                new_version=$(/usr/lib/Acronis/BackupAndRecovery/aakore --version 2>/dev/null | head -1 || echo "Unknown")
                echo "  New version: ${new_version}"
                echo ""

                if [ "$new_version" != "$current_version" ]; then
                    print_success "Agent upgraded: $current_version → $new_version"
                else
                    echo "  ${YELLOW}Version appears unchanged (may already be latest)${NC}"
                fi
            fi

            echo ""

            # Check services
            echo "→ Checking services..."
            sleep 1

            if systemctl is-active --quiet acronis_mms; then
                print_success "Services are running"
            else
                echo "  ${YELLOW}⚠ Services may need restart${NC}"
                echo ""
                echo -n "Restart Acronis services? (yes/no): "
                read -r restart_confirm

                if [[ "$restart_confirm" =~ ^[Yy]([Ee][Ss])?$ ]]; then
                    echo ""
                    echo "→ Restarting services..."
                    systemctl restart aakore
                    systemctl restart acronis_mms
                    systemctl restart acronis_schedule
                    sleep 2

                    if systemctl is-active --quiet acronis_mms; then
                        print_success "Services restarted"
                    else
                        print_error "Service restart failed"
                        echo "Check status: systemctl status acronis_mms"
                    fi
                fi
            fi

            echo ""
            echo -e "${GREEN}${BOLD}✓ Upgrade Complete${NC}"
            echo ""
            echo "The agent has been upgraded and remains registered."
            echo "Backups will continue according to existing schedules."
            echo ""

        else
            print_error "Upgrade failed with exit code $UPGRADE_EXIT_CODE"
            echo ""
            echo "Common issues:"
            echo "  • Agent is already latest version"
            echo "  • Insufficient disk space"
            echo "  • Services in use"
            echo ""
            echo "Check logs for details:"
            echo "  tail -f /var/lib/Acronis/BackupAndRecovery/MMS/mms.0.log"
            echo ""
        fi

        # Cleanup
        echo "→ Cleaning up installation files..."
        cd "$SCRIPT_DIR"
        rm -rf "$INSTALL_DIR"
        echo ""

        press_enter
        ;;

    *)
        echo ""
        echo "Update cancelled"
        press_enter
        ;;
esac
