#!/bin/bash

################################################################################
# Acronis Agent Installer
################################################################################
# Purpose: Download and install Acronis Cyber Protect agent
# Supports:
# - Interactive installation with prompts
# - Unattended installation (-a flag)
# - Skip registration (--skip-registration)
# - Install with token (--token=xxx)
# - Custom service URL (--rain=xxx)
################################################################################

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

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

print_banner "Acronis Agent Installation"

# Check if already installed
if systemctl list-unit-files | grep -q "acronis_mms.service"; then
    echo ""
    echo -e "${YELLOW}${BOLD}⚠ Acronis Already Installed${NC}"
    echo ""
    echo "Acronis Cyber Protect agent is already installed on this system."
    echo ""
    echo -n "Do you want to reinstall/upgrade? (yes/no): "
    read -r reinstall
    if [ "$reinstall" != "yes" ]; then
        echo "Installation cancelled"
        press_enter
        exit 0
    fi
fi

echo ""
echo -e "${BOLD}Acronis Cyber Protect Agent Installation${NC}"
echo ""
echo "This will download and install the latest Acronis agent for Linux (x86_64)."
echo ""
echo -e "${CYAN}Installation Options:${NC}"
echo ""
echo "  1) Interactive installation (default)"
echo "  2) Unattended installation (auto-accept)"
echo "  3) Install and register with token"
echo "  4) Install without registration"
echo "  5) Advanced/Custom installation (specify all flags)"
echo ""
echo -n "Select installation mode [1]: "
read -r install_mode
install_mode="${install_mode:-1}"

# Build installation flags
INSTALL_FLAGS=""
SERVICE_URL="us5-cloud.acronis.com"
REGISTRATION_TOKEN=""

case "$install_mode" in
    2)
        INSTALL_FLAGS="-a"
        echo ""
        echo "Mode: Unattended installation"
        ;;
    3)
        INSTALL_FLAGS="-a"
        echo ""
        echo -e "${BOLD}Register During Installation${NC}"
        echo ""
        echo "Paste your Acronis registration token below."
        echo "To get a token:"
        echo "  1. Log in to Acronis web console"
        echo "  2. Go to: Settings → Registration tokens"
        echo "  3. Create token or copy existing one"
        echo ""
        echo -n "Registration token: "
        read -r REGISTRATION_TOKEN

        # Allow pasting multi-line or trimming whitespace
        REGISTRATION_TOKEN=$(echo "$REGISTRATION_TOKEN" | tr -d '[:space:]')

        if [ -z "$REGISTRATION_TOKEN" ]; then
            print_error "Token is required for this mode"
            press_enter
            exit 1
        fi
        INSTALL_FLAGS="$INSTALL_FLAGS --token=$REGISTRATION_TOKEN"
        echo ""
        echo "Mode: Install with registration token"
        ;;
    4)
        INSTALL_FLAGS="-a --skip-registration"
        echo ""
        echo "Mode: Install without registration"
        ;;
    5)
        # Advanced/Custom mode
        echo ""
        echo -e "${BOLD}Advanced Installation${NC}"
        echo ""
        echo "Build custom installation flags by selecting options."
        echo ""

        # Unattended mode
        echo -n "Unattended install (auto-accept)? (y/n) [y]: "
        read -r use_unattended
        use_unattended="${use_unattended:-y}"
        if [ "$use_unattended" = "y" ]; then
            INSTALL_FLAGS="$INSTALL_FLAGS -a"
        fi

        # Registration options
        echo ""
        echo "Registration:"
        echo "  1) Register with token during install"
        echo "  2) Skip registration (register later)"
        echo "  3) Interactive (installer will prompt)"
        echo -n "Select [3]: "
        read -r reg_choice
        reg_choice="${reg_choice:-3}"

        if [ "$reg_choice" = "1" ]; then
            echo ""
            echo "Paste your Acronis registration token:"
            echo "(Spaces and line breaks will be automatically removed)"
            echo ""
            read -r REGISTRATION_TOKEN
            REGISTRATION_TOKEN=$(echo "$REGISTRATION_TOKEN" | tr -d '[:space:]')

            if [ -n "$REGISTRATION_TOKEN" ]; then
                INSTALL_FLAGS="$INSTALL_FLAGS --token=$REGISTRATION_TOKEN"
            else
                print_error "Token cannot be empty"
                press_enter
                exit 1
            fi
        elif [ "$reg_choice" = "2" ]; then
            INSTALL_FLAGS="$INSTALL_FLAGS --skip-registration"
        fi

        # Additional flags
        echo ""
        echo -e "${BOLD}Additional Options:${NC}"
        echo ""

        # Verbose logging
        echo -n "Enable verbose logging? (y/n) [n]: "
        read -r use_verbose
        if [ "$use_verbose" = "y" ]; then
            INSTALL_FLAGS="$INSTALL_FLAGS --verbose"
        fi

        # Custom flags
        echo ""
        echo "Enter any additional custom flags (or press Enter to skip):"
        echo "Examples: --proxy=http://proxy:8080, --language=en, etc."
        echo ""
        echo -n "Custom flags: "
        read -r custom_flags
        if [ -n "$custom_flags" ]; then
            INSTALL_FLAGS="$INSTALL_FLAGS $custom_flags"
        fi

        echo ""
        echo "Mode: Advanced/Custom installation"
        ;;
    *)
        echo ""
        echo "Mode: Interactive installation"
        ;;
esac

# Ask for service URL (for all modes except skip-registration)
if [[ "$INSTALL_FLAGS" != *"--skip-registration"* ]]; then
    echo ""
    echo -e "${BOLD}Acronis Cloud Region${NC}"
    echo ""
    echo "Common regions:"
    echo "  • us5-cloud.acronis.com (US - Default)"
    echo "  • eu2-cloud.acronis.com (Europe)"
    echo "  • ap1-cloud.acronis.com (Asia Pacific)"
    echo "  • ca1-cloud.acronis.com (Canada)"
    echo ""
    echo -n "Enter service URL [us5-cloud.acronis.com]: "
    read -r input_url
    if [ -n "$input_url" ]; then
        SERVICE_URL="$input_url"
    fi

    # Add --rain flag if token is being used
    if [[ "$INSTALL_FLAGS" == *"--token"* ]]; then
        INSTALL_FLAGS="$INSTALL_FLAGS --rain=$SERVICE_URL"
    fi
fi

echo ""
echo -e "${CYAN}──────────────────────────────────────────────────────────────${NC}"
echo ""
echo -e "${BOLD}Installation Summary:${NC}"
echo ""
echo "  Download URL:    https://${SERVICE_URL}/bc/api/ams/links/agents/redirect"
echo "  Architecture:    x86_64 (64-bit)"
echo "  Install flags:   ${INSTALL_FLAGS:-none}"
echo "  Service URL:     ${SERVICE_URL}"
[ -n "$REGISTRATION_TOKEN" ] && echo "  Token:           ********"
echo ""
echo -e "${CYAN}──────────────────────────────────────────────────────────────${NC}"
echo ""
echo -n "Proceed with installation? (yes/no): "
read -r confirm

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

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

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

# Use timestamped subdirectory for this installation
INSTALL_DIR="$DOWNLOAD_DIR/acronis-install-$(date +%Y%m%d-%H%M%S)"
mkdir -p "$INSTALL_DIR"
cd "$INSTALL_DIR" || exit 1

# Download installer
echo "→ Downloading Acronis agent installer..."
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: ${SERVICE_URL}"
    echo "  • Firewall blocking connection"
    echo ""
    press_enter
    cd /
    rm -rf "$TEMP_DIR"
    exit 1
fi

echo ""

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

# Verify file exists and has size
if [ ! -f "Cyber_Protection_Agent_for_Linux_x86_64.bin" ]; then
    print_error "Installer file not found"
    cd /
    rm -rf "$TEMP_DIR"
    press_enter
    exit 1
fi

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 "Installer file is too small (possibly corrupted)"
    cd /
    rm -rf "$TEMP_DIR"
    press_enter
    exit 1
fi

# Run installer
echo "→ Running Acronis installer..."
echo ""
echo -e "${DIM}──────────────────────────────────────────────────────────────${NC}"

if [ -z "$INSTALL_FLAGS" ]; then
    # Interactive mode - run directly
    ./Cyber_Protection_Agent_for_Linux_x86_64.bin
else
    # Unattended mode - need to pass flags properly
    ./Cyber_Protection_Agent_for_Linux_x86_64.bin $INSTALL_FLAGS
fi

INSTALL_EXIT_CODE=$?

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

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

    # Start services
    echo "→ Starting Acronis services..."
    systemctl start aakore
    systemctl start acronis_mms
    systemctl start acronis_schedule
    echo ""

    # Check if services started
    sleep 2
    if systemctl is-active --quiet acronis_mms; then
        print_success "Services started successfully"
        echo ""

        # Show next steps
        echo -e "${BOLD}Next Steps:${NC}"
        echo ""

        if [ "$install_mode" = "4" ]; then
            echo "  1. Register the agent with Acronis Cloud"
            echo "     → Select 'Register with Cloud' from Acronis menu"
            echo ""
        fi

        echo "  2. Configure backup plans in Acronis web console"
        echo "     → Visit: https://${SERVICE_URL}"
        echo ""
        echo "  3. Check agent status"
        echo "     → Select 'Check Agent Status' from Acronis menu"
        echo ""
    else
        print_error "Services failed to start"
        echo ""
        echo "Check logs for details:"
        echo "  tail -f /var/lib/Acronis/BackupAndRecovery/MMS/mms.0.log"
        echo ""
    fi

else
    print_error "Installation failed with exit code $INSTALL_EXIT_CODE"
    echo ""
    echo "Check the output above for error details."
    echo ""
    echo "Common issues:"
    echo "  • Incompatible system (requires 64-bit Linux)"
    echo "  • Insufficient disk space"
    echo "  • Conflicting backup software"
    echo "  • Invalid registration token"
    echo ""
fi

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

echo ""
press_enter
