#!/bin/bash
#
# batuta-compatibility-checker.sh
#
# Description: Checks system compatibility with Batuta Agent for Linux systems
#
# Usage: ./batuta-compatibility-checker.sh [-d domain] [-p proxy] [-D]
#   -d domain    Agent Server Domain (required if not in interactive mode)
#   -p proxy     Optional proxy URL for web requests
#   -D           Debug mode to show detailed information for troubleshooting
#
# Note: This script must be run with root privileges (sudo)

# Default config values
CURRENT_VERSION="1.0.0"
BATUTA_API_URL="https://api.batuta.io"
PAIRING_URL="https://pairing.batuta.io/version"
CDN_URL="https://cdn-batuta.nyc3.cdn.digitaloceanspaces.com/batuta-agent-installer.sh"

compatibility_failed=false
is_interactive=false
debug_mode=false
domain=""
proxy=""

# Print header
echo -e "Batuta Agent Compatibility Checker ($CURRENT_VERSION)\n"

# Function to display usage information
usage() {
    echo "Usage: $0 [-d domain] [-p proxy] [-D]"
    echo "  -d domain    Agent Server Domain (required if not in interactive mode)"
    echo "  -p proxy     Optional proxy URL for web requests"
    echo "  -D           Debug mode to show detailed information for troubleshooting"
    exit 1
}

# Parse command line arguments
while getopts "d:p:D" opt; do
    case $opt in
        d) domain="$OPTARG" ;;
        p) proxy="$OPTARG" ;;
        D) debug_mode=true ;;
        *) usage ;;
    esac
done

# Function to prompt user to continue
prompt_continue() {
    if [ "$is_interactive" = true ]; then
        echo -e "\nPress Enter to exit..."
        read -r
    fi
}

# Function to print success message
print_success() {
    local message="$1"
    if [ "$debug_mode" = true ]; then
        echo -e "\e[32mOK ($message)\e[0m"
    else
        echo -e "\e[32mOK\e[0m"
    fi
}

# Function to print failure message
print_failure() {
    local message="$1"
    echo -e "\e[31m$message\e[0m"
    compatibility_failed=true
}

# Function to check OS type and architecture
test_os_architecture() {
    echo -n "Checking OS type... "

    os_type=$(uname -s)
    if [[ "$os_type" != "Linux" ]]; then
        print_failure "OS type not compatible: Linux is required. Found: $os_type"
        return
    else
        print_success "$os_type"
    fi

    echo -n "Checking OS architecture... "
    arch=$(uname -m)
    if [[ "$arch" == "x86_64" || "$arch" == "amd64" ]]; then
        print_success "$arch"
    else
        print_failure "OS architecture not compatible: 64-bit Linux is required. Found: $arch"
    fi
}

# Function to check Bash version
test_bash_version() {
    echo -n "Checking Bash version... "

    # Extract major and minor version
    bash_version=${BASH_VERSION%%[^0-9.]*}
    bash_major=${bash_version%%.*}
    bash_version=${bash_version#*.}
    bash_minor=${bash_version%%.*}

    if (( bash_major > 4 || (bash_major == 4 && bash_minor >= 0) )); then
        print_success "$BASH_VERSION"
    else
        print_failure "Bash version not compatible: 4.0 or higher is required. Found: $BASH_VERSION"
    fi
}

# Function to check if curl is installed with SSL support
test_curl_ssl() {
    echo -n "Checking curl with SSL support... "

    if ! command -v curl &> /dev/null; then
        print_failure "curl is not installed"
        return
    fi

    ssl_support=$(curl -V | grep -i ssl)
    if [ -n "$ssl_support" ]; then
        print_success "$ssl_support"
    else
        print_failure "curl does not have SSL support"
    fi
}

# Function to check connection to a URL
test_url_connection() {
    local url="$1"
    local use_head="${2:-true}"
    local name="$3"

    echo -n "Checking connection with ${name:-$url}... "

    local curl_cmd="curl -s"
    if [ "$use_head" = true ]; then
        curl_cmd="$curl_cmd -I"
    fi

    if [ -n "$proxy" ]; then
        curl_cmd="$curl_cmd -x $proxy"
    fi

    local response
    if [ "$use_head" = true ]; then
        response=$($curl_cmd -o /dev/null -w "%{http_code}" "$url")
    else
        response=$($curl_cmd -o /dev/null -w "%{http_code}" "$url")
    fi

    if [ "$response" = "200" ]; then
        print_success "HTTP $response"
    else
        print_failure "Failed to connect to $url (HTTP $response)"
        if [ "$debug_mode" = true ]; then
            $curl_cmd "$url"
        fi
    fi
}

# Function to check connection to agent server
test_agent_server_connection() {
    echo -n "Checking connection with agent's server... "

    # First check if netcat is available
    if command -v nc &> /dev/null; then
        if nc -zw3 "$domain" 80 &>/dev/null; then
            print_success "Port 80 is open (using netcat)"
            return
        fi
    fi

    # Fallback to using curl if netcat is not available
    if curl -s --connect-timeout 5 --max-time 10 "http://$domain" -o /dev/null; then
        print_success "Port 80 is open (using curl)"
    else
        print_failure "Unable to connect with agent's server at $domain on port 80"
    fi
}

# Check if domain is provided or prompt for it
if [ -z "$domain" ]; then
    is_interactive=true
    echo -n "Please, provide the agent's server domain: "
    read -r domain

    if [ ${#domain} -lt 5 ]; then
        echo -e "\e[31mSorry, you must provide a valid domain for the agent's server.\e[0m"
        prompt_continue
        exit 1
    fi

    if [ -z "$proxy" ]; then
        echo -n "Does this host navigate through a proxy? (y/n): "
        read -r needs_proxy

        if [[ "$needs_proxy" =~ ^[Yy](es)?$ ]]; then
            echo -n "Please, provide the proxy URL: "
            read -r proxy

            if [ ${#proxy} -lt 5 ]; then
                echo -e "\e[31mSorry, you must provide a valid proxy URL.\e[0m"
                prompt_continue
                exit 1
            fi
        fi
    fi
fi

# Check if running as root
if [ "$EUID" -ne 0 ]; then
    echo -n "Checking root privileges... "
    print_failure "This script must be run as root"
    echo "Please run this script with sudo or as the root user."
    prompt_continue
    exit 1
fi

# Function to check for required packages
test_required_packages() {
    echo -n "Checking for required packages... "

    missing_packages=()
    required_packages=("curl" "openssl" "ca-certificates" "sed" "tar")

    for pkg in "${required_packages[@]}"; do
        # Different distros have different ways to check for packages
        # Try a few common methods
        if command -v dpkg &> /dev/null; then
            # Debian/Ubuntu
            if ! dpkg -l | grep -q "ii  $pkg"; then
                missing_packages+=("$pkg")
            fi
        elif command -v rpm &> /dev/null; then
            # RHEL/CentOS/Fedora
            if ! rpm -q "$pkg" &> /dev/null; then
                missing_packages+=("$pkg")
            fi
        elif command -v pacman &> /dev/null; then
            # Arch Linux
            if ! pacman -Q "$pkg" &> /dev/null; then
                missing_packages+=("$pkg")
            fi
        else
            # Fallback to checking if the command exists
            # This is not perfect but better than nothing
            if ! command -v "$pkg" &> /dev/null; then
                missing_packages+=("$pkg")
            fi
        fi
    done

    if [ ${#missing_packages[@]} -eq 0 ]; then
        print_success "All required packages are installed"
    else
        print_failure "Missing required packages: ${missing_packages[*]}"
    fi
}

# Run compatibility checks
test_os_architecture
test_bash_version
test_curl_ssl
test_required_packages
test_url_connection "$BATUTA_API_URL" true "API"
test_url_connection "$PAIRING_URL" false "Pairing Server"
test_url_connection "$CDN_URL" true "CDN"
test_agent_server_connection

# Display final result
if [ "$compatibility_failed" = true ]; then
    echo -e "\n\e[31mOops, looks like some checks failed. BatutaAgent installation would most likely fail.\e[0m"
    echo -e "\e[31mPlease, contact support and provide them with the output of these checks.\e[0m"
    prompt_continue
    exit 1
else
    echo -e "\n\e[32mAll checks passed! BatutaAgent installation should work just fine.\e[0m"
    prompt_continue
    exit 0
fi
