#!/bin/bash

################################################################################
# Acronis Agent Status Checker
################################################################################
# Purpose: Check status of all Acronis Cyber Protect services
# Services monitored:
# - aakore (Acronis Agent Core)
# - acronis_mms (Management Service)
# - acronis_schedule (Scheduler)
# - active-protection.service (Ransomware Protection)
################################################################################

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

echo ""
echo -e "${BOLD}Checking Acronis Cyber Protect Services...${NC}"
echo ""

# Array of services to check
declare -a SERVICES=(
    "aakore:Acronis Agent Core"
    "acronis_mms:Management Service"
    "acronis_schedule:Backup Scheduler"
    "active-protection:Ransomware Protection"
)

# Track overall status
all_running=true
any_installed=false

# Function to check service status
check_service_status() {
    local service_name="$1"
    local service_desc="$2"

    # Check if service exists
    if systemctl list-unit-files | grep -q "^${service_name}.service"; then
        any_installed=true

        # Get service status
        if systemctl is-active --quiet "$service_name"; then
            echo -e "  ${GREEN}●${NC} ${BOLD}${service_desc}${NC}"
            echo -e "     Status: ${GREEN}RUNNING${NC}"

            # Get uptime
            local uptime=$(systemctl show "$service_name" -p ActiveEnterTimestamp --value)
            if [ -n "$uptime" ]; then
                echo -e "     Uptime: ${uptime}"
            fi

            # Get PID
            local pid=$(systemctl show "$service_name" -p MainPID --value)
            if [ "$pid" != "0" ]; then
                echo -e "     PID:    ${pid}"
            fi
        else
            all_running=false
            echo -e "  ${RED}●${NC} ${BOLD}${service_desc}${NC}"
            echo -e "     Status: ${RED}STOPPED${NC}"

            # Check if failed
            if systemctl is-failed --quiet "$service_name"; then
                echo -e "     ${RED}[FAILED]${NC} - Service has errors"
            fi
        fi
        echo ""
    elif service "$service_name" status &>/dev/null; then
        # Fallback to service command for older systems
        any_installed=true
        if service "$service_name" status | grep -q "running"; then
            echo -e "  ${GREEN}●${NC} ${BOLD}${service_desc}${NC}"
            echo -e "     Status: ${GREEN}RUNNING${NC}"
        else
            all_running=false
            echo -e "  ${RED}●${NC} ${BOLD}${service_desc}${NC}"
            echo -e "     Status: ${RED}STOPPED${NC}"
        fi
        echo ""
    fi
}

# Check each service
for service_entry in "${SERVICES[@]}"; do
    IFS=':' read -r service_name service_desc <<< "$service_entry"
    check_service_status "$service_name" "$service_desc"
done

# Check if Acronis is even installed
if [ "$any_installed" = false ]; then
    echo -e "${YELLOW}${BOLD}⚠ Acronis Agent Not Installed${NC}"
    echo ""
    echo "Acronis Cyber Protect is not installed on this system."
    echo ""
    echo "To install:"
    echo "  1. Return to Backup & Recovery menu"
    echo "  2. Select 'Acronis Management'"
    echo "  3. Choose 'Install Acronis Agent'"
    echo ""
    press_enter
    exit 0
fi

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

# Overall status summary
if [ "$all_running" = true ]; then
    echo -e "${GREEN}${BOLD}✓ All Services Running${NC}"
    echo ""
    echo "Acronis Cyber Protect is operational and ready for backups."
else
    echo -e "${YELLOW}${BOLD}⚠ Some Services Not Running${NC}"
    echo ""
    echo "Some Acronis services are stopped. You may want to:"
    echo "  • Start services: Select 'Service Management' from Acronis menu"
    echo "  • Check logs: Select 'View Logs' for error details"
    echo "  • Restart services: Try restarting all services"
fi

echo ""

# Check agent registration status
echo -e "${BOLD}Agent Registration:${NC}"
if [ -f "/var/lib/Acronis/BackupAndRecovery/MMS/user.config" ]; then
    # Check for registration info in user.config
    if grep -q "<registration>" "/var/lib/Acronis/BackupAndRecovery/MMS/user.config" 2>/dev/null; then
        reg_address=$(grep -oP '<address>\K[^<]+' /var/lib/Acronis/BackupAndRecovery/MMS/user.config 2>/dev/null)
        reg_env=$(grep -oP '<environment>\K[^<]+' /var/lib/Acronis/BackupAndRecovery/MMS/user.config 2>/dev/null)

        if [ -n "$reg_address" ]; then
            echo -e "  ${GREEN}✓${NC} Agent is registered with Acronis Cloud"
            echo -e "  URL: ${reg_address}"
            [ -n "$reg_env" ] && echo -e "  Environment: ${reg_env}"
        else
            echo -e "  ${YELLOW}⚠${NC} Registration incomplete"
        fi
    else
        echo -e "  ${YELLOW}⚠${NC} Agent not registered"
    fi
else
    echo -e "  ${YELLOW}⚠${NC} Configuration file not found"
fi

echo ""

# Check active ports
echo -e "${BOLD}Network Connectivity:${NC}"

# Check for actual Acronis listening ports (deduplicate IPv4/IPv6)
acronis_ports=$(netstat -tlnp 2>/dev/null | grep -E "(acronis|mms|aakore)" | awk '{
    split($4, addr, ":");
    port = addr[length(addr)];
    if (!seen[port]++) {
        print $4 " " $7;
    }
}')

if [ -n "$acronis_ports" ]; then
    echo "Active Acronis services:"
    echo "$acronis_ports" | while read -r addr process; do
        port=$(echo "$addr" | grep -oP ':\K[0-9]+$' 2>/dev/null)
        if echo "$addr" | grep -q "127.0.0.1\|::1"; then
            # Local-only port
            if [ "$port" = "9850" ]; then
                echo -e "  ${GREEN}✓${NC} Port $port (localhost) - MMS Service"
            else
                echo -e "  ${GREEN}✓${NC} Port $port (localhost) - $(basename "$process" | cut -d/ -f2)"
            fi
        else
            echo -e "  ${GREEN}✓${NC} Port $port - $(basename "$process" | cut -d/ -f2)"
        fi
    done
else
    echo -e "  ${YELLOW}⚠${NC} No Acronis ports detected"
fi

echo ""

# Check outbound connectivity to cloud (port 443)
echo ""
echo -e "${BOLD}Cloud Connectivity Test:${NC}"

if command -v curl >/dev/null 2>&1; then
    reg_url=$(grep -oP '<address>\K[^<]+' /var/lib/Acronis/BackupAndRecovery/MMS/user.config 2>/dev/null)
    if [ -n "$reg_url" ]; then
        echo -n "  Testing ${reg_url}... "

        http_code=$(timeout 5 curl -s -o /dev/null -w "%{http_code}" "$reg_url" 2>/dev/null)

        if [ "$http_code" -ge 200 ] && [ "$http_code" -lt 500 ]; then
            echo -e "${GREEN}✓ Reachable${NC} (HTTP $http_code)"
        else
            echo -e "${RED}✗ Unreachable${NC}"
            echo -e "  ${YELLOW}⚠${NC} Cannot reach Acronis cloud (firewall/network issue)"
            echo "  • Check internet connectivity"
            echo "  • Verify firewall allows HTTPS (port 443)"
            echo "  • Test manually: curl -I $reg_url"
        fi
    else
        echo -e "  ${YELLOW}⚠${NC} Cloud URL not found in config"
    fi
else
    echo -e "  ${YELLOW}⚠${NC} curl not installed (cannot test connectivity)"
fi

echo ""

# Check cloud storage quota
echo -e "${BOLD}Cloud Backup Storage:${NC}"
if command -v acrocmd >/dev/null 2>&1; then
    vault_info=$(acrocmd list vaults 2>/dev/null | tail -n +3 | head -1)

    if [ -n "$vault_info" ]; then
        # Extract storage info from vault output
        vault_name=$(echo "$vault_info" | awk '{print $1}')
        vault_free_val=$(echo "$vault_info" | awk '{print $4}')
        vault_free_unit=$(echo "$vault_info" | awk '{print $5}')
        vault_occupied=$(echo "$vault_info" | awk '{print $6, $7}')

        echo -e "  Vault:        ${vault_name}"
        echo -e "  Available:    ${vault_free_val} ${vault_free_unit}"

        # Show occupied if available, otherwise note it's not synced
        if [ "$vault_occupied" != "0 GB" ]; then
            echo -e "  Used:         ${vault_occupied}"
        else
            echo -e "  Used:         ${DIM}(Check web console for accurate usage)${NC}"
        fi
    else
        echo -e "  ${YELLOW}⚠${NC} No vault information available"
        echo -e "  ${DIM}(Cloud storage visible after first backup)${NC}"
    fi
else
    echo -e "  ${YELLOW}⚠${NC} acrocmd not available"
fi

echo ""

# Check local disk space
echo -e "${BOLD}Local Storage Status:${NC}"
if [ -d "/var/lib/Acronis" ]; then
    backup_dir_size=$(du -sh /var/lib/Acronis 2>/dev/null | awk '{print $1}')
    echo -e "  Agent data:   ${backup_dir_size} (local cache/logs/config)"

    # Check free space on partition
    free_space=$(df -h /var/lib/Acronis | tail -1 | awk '{print $4}')
    use_percent=$(df -h /var/lib/Acronis | tail -1 | awk '{print $5}' | tr -d '%')

    echo -e "  Free space:   ${free_space} (on root partition)"

    if [ -n "$use_percent" ] && [ "$use_percent" -gt 90 ] 2>/dev/null; then
        echo -e "  ${RED}⚠ Warning: Disk usage at ${use_percent}%${NC}"
    fi
fi

echo ""
press_enter
