#!/bin/bash

################################################################################
# Acronis Agent Uninstaller
################################################################################
# Purpose: Safely uninstall Acronis Cyber Protect agent
# Process:
# 1. Stop all Acronis services
# 2. Unregister from cloud (optional)
# 3. Remove Acronis packages
# 4. Clean up data directories (optional)
################################################################################

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

# Check if Acronis is installed
if ! systemctl list-unit-files | grep -q "acronis_mms.service"; then
    echo ""
    echo -e "${YELLOW}⚠ Acronis Not Installed${NC}"
    echo ""
    echo "Acronis Cyber Protect does not appear to be installed on this system."
    echo ""
    press_enter
    exit 0
fi

echo ""
echo -e "${RED}${BOLD}⚠️  WARNING ⚠️${NC}"
echo ""
echo "This will completely remove Acronis Cyber Protect from this system."
echo ""
echo -e "${BOLD}What will be removed:${NC}"
echo "  • All Acronis services (aakore, mms, schedule, active-protection)"
echo "  • Acronis software packages"
echo "  • Agent registration (if selected)"
echo "  • Backup data and logs (if selected)"
echo ""
echo -e "${RED}This action cannot be easily undone!${NC}"
echo ""
echo -e "${CYAN}──────────────────────────────────────────────────────────────${NC}"
echo ""

# Confirm uninstallation
echo -n "Type 'uninstall' to confirm removal: "
read -r confirm

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

echo ""
echo -e "${BOLD}Uninstallation Options:${NC}"
echo ""

# Ask about data retention
echo -n "Remove backup data and logs? (yes/no) [no]: "
read -r remove_data
remove_data="${remove_data:-no}"

echo ""
echo -n "Unregister from Acronis Cloud? (yes/no) [yes]: "
read -r unregister
unregister="${unregister:-yes}"

echo ""
echo -e "${CYAN}──────────────────────────────────────────────────────────────${NC}"
echo ""
echo -e "${BOLD}Uninstallation Summary:${NC}"
echo ""
echo "  Stop services:       Yes"
echo "  Remove software:     Yes"
echo "  Unregister agent:    ${unregister}"
echo "  Remove data/logs:    ${remove_data}"
echo ""
echo -e "${CYAN}──────────────────────────────────────────────────────────────${NC}"
echo ""
echo -n "Proceed with uninstallation? (yes/no): "
read -r final_confirm

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

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

# Stop all services
echo "→ Stopping Acronis services..."
systemctl stop active-protection.service 2>/dev/null
systemctl stop acronis_schedule 2>/dev/null
systemctl stop acronis_mms 2>/dev/null
systemctl stop aakore 2>/dev/null
service acronis_mms stop 2>/dev/null

sleep 2

if systemctl is-active --quiet acronis_mms; then
    print_error "Warning: Some services may still be running"
else
    print_success "Services stopped"
fi

echo ""

# Unregister from cloud if requested
if [ "$unregister" = "yes" ]; then
    echo "→ Unregistering from Acronis Cloud..."

    if [ -f "/usr/lib/Acronis/RegisterAgentTool/RegisterAgent" ]; then
        if /usr/lib/Acronis/RegisterAgentTool/RegisterAgent -o unregister 2>/dev/null; then
            print_success "Agent unregistered"
        else
            echo "  ${YELLOW}Note: Unregistration may have failed (continuing anyway)${NC}"
        fi
    else
        echo "  ${YELLOW}Note: Registration tool not found (skipping)${NC}"
    fi

    echo ""
fi

# Disable services
echo "→ Disabling Acronis services..."
systemctl disable aakore 2>/dev/null
systemctl disable acronis_mms 2>/dev/null
systemctl disable acronis_schedule 2>/dev/null
systemctl disable active-protection.service 2>/dev/null
echo "  ${GREEN}✓${NC} Services disabled"
echo ""

# Remove packages
echo "→ Removing Acronis packages..."

# Try different package managers
if command -v dpkg &>/dev/null; then
    # Debian/Ubuntu
    dpkg -l | grep -i acronis | awk '{print $2}' | while read -r pkg; do
        echo "  Removing: $pkg"
        dpkg --purge "$pkg" 2>/dev/null
    done
elif command -v rpm &>/dev/null; then
    # RedHat/CentOS
    rpm -qa | grep -i acronis | while read -r pkg; do
        echo "  Removing: $pkg"
        rpm -e "$pkg" 2>/dev/null
    done
fi

print_success "Packages removed"
echo ""

# Remove data directories if requested
if [ "$remove_data" = "yes" ]; then
    echo "→ Removing Acronis data and logs..."

    declare -a DATA_DIRS=(
        "/var/lib/Acronis"
        "/usr/lib/Acronis"
        "/etc/Acronis"
        "/opt/acronis"
    )

    for dir in "${DATA_DIRS[@]}"; do
        if [ -d "$dir" ]; then
            size=$(du -sh "$dir" 2>/dev/null | awk '{print $1}')
            echo "  Removing: $dir (${size})"
            rm -rf "$dir" 2>/dev/null
        fi
    done

    print_success "Data directories removed"
    echo ""
fi

# Clean up systemd
echo "→ Cleaning up system configuration..."
systemctl daemon-reload
echo "  ${GREEN}✓${NC} systemd reloaded"
echo ""

# Final verification
echo -e "${CYAN}──────────────────────────────────────────────────────────────${NC}"
echo ""
echo -e "${GREEN}${BOLD}✓ Uninstallation Complete${NC}"
echo ""

# Check if anything remains
remaining=0

if systemctl list-unit-files | grep -q "acronis"; then
    echo -e "${YELLOW}⚠ Some service files may still be present${NC}"
    ((remaining++))
fi

if [ -d "/var/lib/Acronis" ] || [ -d "/usr/lib/Acronis" ]; then
    echo -e "${YELLOW}⚠ Some directories were not removed${NC}"
    ((remaining++))
fi

if [ "${remaining:-0}" -eq 0 ]; then
    echo "Acronis Cyber Protect has been completely removed from this system."
else
    echo ""
    echo "Uninstallation mostly complete, but some files may remain."
    echo "This is usually safe and won't affect system operation."
fi

echo ""

# Show what was kept
if [ "$remove_data" = "no" ]; then
    echo -e "${BOLD}Retained Data:${NC}"
    echo ""
    echo "Backup data and logs were kept as requested:"
    if [ -d "/var/lib/Acronis" ]; then
        data_size=$(du -sh /var/lib/Acronis 2>/dev/null | awk '{print $1}')
        echo "  Location: /var/lib/Acronis"
        echo "  Size:     $data_size"
        echo ""
        echo "To remove this data later:"
        echo "  rm -rf /var/lib/Acronis"
    fi
    echo ""
fi

echo "To reinstall Acronis in the future:"
echo "  1. Return to Backup & Recovery menu"
echo "  2. Select 'Acronis Management'"
echo "  3. Choose 'Install Acronis Agent'"
echo ""

press_enter
