#!/bin/bash

################################################################################
# Acronis Agent Registration
################################################################################
# Purpose: Register Acronis agent with Acronis Cloud
# Command: /usr/lib/Acronis/RegisterAgentTool/RegisterAgent
# Flags:
#   -o register       - Operation: register
#   -t cloud          - Type: cloud-based
#   -a <url>          - Service URL
#   --token <token>   - Registration token
################################################################################

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 Registration"

# Check if agent is installed
if [ ! -f "/usr/lib/Acronis/RegisterAgentTool/RegisterAgent" ]; then
    echo ""
    print_error "Acronis agent is not installed"
    echo ""
    echo "Please install the agent first:"
    echo "  1. Return to Acronis Management menu"
    echo "  2. Select 'Install Acronis Agent'"
    echo ""
    press_enter
    exit 1
fi

echo ""

# Check current registration status
echo -e "${BOLD}Current Registration Status:${NC}"
echo ""

if [ -f "/etc/Acronis/Global.config" ]; then
    if grep -q "CloudUrl" "/etc/Acronis/Global.config" 2>/dev/null; then
        echo -e "  ${GREEN}✓${NC} Agent is currently registered"

        # Extract current cloud URL
        current_url=$(grep -oP 'CloudUrl[>="].*?https://[^"<]+' /etc/Acronis/Global.config 2>/dev/null | grep -oP 'https://[^"<]+' | head -1)
        if [ -n "$current_url" ]; then
            echo -e "  Current URL: ${current_url}"
        fi

        echo ""
        echo -e "${YELLOW}⚠ Agent is already registered${NC}"
        echo ""
        echo "Do you want to:"
        echo "  1) Keep current registration"
        echo "  2) Re-register (will overwrite current registration)"
        echo ""
        echo -n "Select [1]: "
        read -r choice
        choice="${choice:-1}"

        if [ "$choice" = "1" ]; then
            echo ""
            echo "Keeping current registration"
            press_enter
            exit 0
        fi

        echo ""
        echo "Proceeding with re-registration..."
    else
        echo -e "  ${YELLOW}○${NC} Agent is not registered"
    fi
else
    echo -e "  ${YELLOW}○${NC} No configuration found"
fi

echo ""
echo -e "${CYAN}──────────────────────────────────────────────────────────────${NC}"
echo ""
echo -e "${BOLD}Agent Registration${NC}"
echo ""
echo "You'll need:"
echo "  • Acronis Cloud service URL (e.g., us5-cloud.acronis.com)"
echo "  • Registration token from Acronis web console"
echo ""
echo "To get a registration token:"
echo "  1. Log in to Acronis web console"
echo "  2. Go to Settings → Registration tokens"
echo "  3. Create a new token or copy existing one"
echo ""
echo -e "${CYAN}──────────────────────────────────────────────────────────────${NC}"
echo ""

# Get service URL
echo -n "Enter Acronis Cloud service URL [us5-cloud.acronis.com]: "
read -r service_url
service_url="${service_url:-us5-cloud.acronis.com}"

# Validate URL format
if [[ ! "$service_url" =~ ^[a-z0-9.-]+\.acronis\.com$ ]]; then
    print_error "Invalid service URL format"
    echo ""
    echo "Expected format: region-cloud.acronis.com"
    echo "Examples:"
    echo "  • us5-cloud.acronis.com"
    echo "  • eu2-cloud.acronis.com"
    echo "  • ap1-cloud.acronis.com"
    echo ""
    press_enter
    exit 1
fi

# Get registration token
echo ""
echo -n "Enter registration token: "
read -r reg_token

if [ -z "$reg_token" ]; then
    print_error "Registration token is required"
    press_enter
    exit 1
fi

# Confirm registration
echo ""
echo -e "${CYAN}──────────────────────────────────────────────────────────────${NC}"
echo ""
echo -e "${BOLD}Registration Summary:${NC}"
echo ""
echo "  Service URL:  https://${service_url}"
echo "  Token:        ${reg_token:0:8}...${reg_token: -4}"
echo ""
echo -e "${CYAN}──────────────────────────────────────────────────────────────${NC}"
echo ""
echo -n "Proceed with registration? (yes/no): "
read -r confirm

if [ "$confirm" != "yes" ]; then
    echo ""
    print_error "Registration cancelled"
    press_enter
    exit 0
fi

echo ""
echo -e "${BOLD}Registering Agent...${NC}"
echo ""

# Run registration command
REGISTER_CMD="/usr/lib/Acronis/RegisterAgentTool/RegisterAgent"
REGISTER_ARGS="-o register -t cloud -a https://${service_url} --token ${reg_token}"

echo "→ Contacting Acronis Cloud..."
echo ""
echo -e "${DIM}──────────────────────────────────────────────────────────────${NC}"

# Execute registration
if $REGISTER_CMD $REGISTER_ARGS; then
    REG_EXIT_CODE=$?
else
    REG_EXIT_CODE=$?
fi

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

# Check result
if [ "${REG_EXIT_CODE:-0}" -eq 0 ]; then
    print_success "Registration successful!"
    echo ""

    # Restart services to apply registration
    echo "→ Restarting Acronis services..."
    systemctl restart acronis_mms
    systemctl restart aakore
    sleep 2

    if systemctl is-active --quiet acronis_mms; then
        print_success "Services restarted successfully"
        echo ""

        echo -e "${BOLD}Agent Registered Successfully!${NC}"
        echo ""
        echo "Next steps:"
        echo "  1. Log in to Acronis web console:"
        echo "     → https://${service_url}"
        echo ""
        echo "  2. Find this agent in the device list"
        echo "     → Navigate to: Devices → All devices"
        echo ""
        echo "  3. Assign backup plans to this agent"
        echo "     → Select device → Protection → Add plan"
        echo ""
        echo "  4. Check agent status from this toolkit"
        echo "     → Select 'Check Agent Status' from Acronis menu"
        echo ""
    else
        print_error "Services failed to restart"
        echo ""
        echo "Registration may have succeeded but services need attention."
        echo "Check logs: tail -f /var/lib/Acronis/BackupAndRecovery/MMS/mms.0.log"
        echo ""
    fi

else
    print_error "Registration failed with exit code $REG_EXIT_CODE"
    echo ""
    echo "Common issues:"
    echo "  • Invalid registration token"
    echo "  • Incorrect service URL"
    echo "  • Network connectivity issues"
    echo "  • Firewall blocking connection to Acronis Cloud"
    echo "  • Token already used or expired"
    echo ""
    echo "Troubleshooting:"
    echo "  1. Verify token in Acronis web console"
    echo "  2. Check network connectivity:"
    echo "     curl -I https://${service_url}"
    echo ""
    echo "  3. Check agent logs:"
    echo "     tail -f /var/lib/Acronis/BackupAndRecovery/MMS/mms.0.log"
    echo ""
fi

press_enter
