#!/bin/bash
################################################################################
# Monofor Installation Script - v2026.02
# Copyright (C) 2017-2026 Monofor, Inc. All rights reserved.
#
# Description: Enterprise-grade installation script with professional
#              code structure, comprehensive error handling, and optimization
#
#Build=202605041828
#Version=v2026.05
################################################################################

set -euo pipefail
trap 'handle_error "Script failed on line $LINENO" "$EXIT_ERROR"' ERR

################################################################################
# CONSTANTS AND CONFIGURATION
################################################################################

# Script Information
readonly SCRIPT_NAME="$(basename "$0")"
readonly SCRIPT_VERSION="v2026.05"
readonly SCRIPT_BUILD="202605041828"

# Exit Codes
readonly EXIT_SUCCESS=0
readonly EXIT_ERROR=1
readonly EXIT_INVALID_ARGS=2
readonly EXIT_PERMISSION_DENIED=3
readonly EXIT_DEPENDENCY_MISSING=4
readonly EXIT_NETWORK_ERROR=5

# Network Configuration
readonly CURL_CONNECT_TIMEOUT=10
readonly CURL_MAX_TIME_CHECK=20
readonly CURL_MAX_TIME_DOWNLOAD=30
readonly CURL_RETRY_COUNT=3

# File Paths and Directories
readonly SCRIPT_DIR="/usr/bin"
readonly VAR_LOG_DIR="/var/log"
readonly TMP_DIR="/tmp"
readonly LOG_PREFIX="monofor-install"
readonly LOG_SUFFIX="$(date +%F)"

# Repository and Download URLs
readonly REPO_URL="https://cr.monofor.com"
readonly DOWNLOAD_URL="https://download.monofor.com"
readonly SERVICES_URL="https://services.monofor.com"
readonly DOCKER_URL="https://download.docker.com"

# Installation Directories
readonly INST_TMP_DIR="${TMP_DIR}/monofor-installation"
readonly TOOLS_TMP_DIR="${TMP_DIR}/monofor-tools"

# UI Configuration
readonly MESSAGE_WIDTH=30
readonly BORDER_CHAR="#"
readonly BORDER_LENGTH=60
readonly PROGRESS_WIDTH=50

# Color Codes
readonly ESC=$(printf '\033')
readonly RESET="${ESC}[0m"
readonly BLUE="${ESC}[1;36m"
readonly RED="${ESC}[1;31m"
readonly GREEN="${ESC}[1;32m"
readonly YELLOW="${ESC}[1;33m"

# Log File Configuration
logFile="${VAR_LOG_DIR}/${LOG_PREFIX}-${LOG_SUFFIX}.log"
if ! touch "$logFile" 2>/dev/null; then
  logFile="${TMP_DIR}/${LOG_PREFIX}-${LOG_SUFFIX}.log"
  touch "$logFile"
fi
chmod 600 "$logFile"

# Base URL Version
VERSION="latest"
baseUrl="${DOWNLOAD_URL}/install/${VERSION}"

################################################################################
# CORE LOGGING FUNCTIONS
################################################################################

################################################################################
# Function: log_message
# Description: Write message to log file with timestamp
# Parameters:
#   $1 - Log level (INFO, WARN, ERROR, DEBUG)
#   $2 - Message text
# Returns: None
# Exit Codes: 0 on success
################################################################################
log_message() {
  local level="$1"
  local message="$2"
  local timestamp
  timestamp=$(date '+%F %H:%M:%S.%3N')
  
  local log_entry="[$timestamp] [$level] - $message"
  echo "$log_entry" >> "$logFile"
}

################################################################################
# Function: log_and_print
# Description: Log message and print to console
# Parameters:
#   $1 - Log level
#   $2 - Message text
#   $3 - Optional: Message type (info/warn/error)
# Returns: None
################################################################################
log_and_print() {
  local level="$1"
  local message="$2"
  local msg_type="${3:-info}"
  
  log_message "$level" "$message"
  
  case "$msg_type" in
    error)
      printf "%s%s%s\n" "$RED" "$message" "$RESET" >&2
    ;;
    warn)
      printf "%s%s%s\n" "$YELLOW" "$message" "$RESET"
    ;;
    *)
      printf "%s%s%s\n" "$BLUE" "$message" "$RESET"
    ;;
  esac
}

################################################################################
# UTILITY FUNCTIONS
################################################################################

################################################################################
# Function: check_root
# Description: Verify script is running as root
# Parameters: None
# Returns: 0 if root, exits otherwise
################################################################################
check_root() {
  if [[ $EUID -ne 0 ]]; then
    log_and_print "ERROR" "This script must be run as root" "error"
    exit "$EXIT_PERMISSION_DENIED"
  fi
}

################################################################################
# Function: check_dependency
# Description: Verify required command is installed
# Parameters: $1 - Command name
# Returns: 0 if found, 1 if not
################################################################################
check_dependency() {
  local cmd="$1"
  if ! command -v "$cmd" &>/dev/null; then
    log_and_print "ERROR" "Required command not found: $cmd" "error"
    return 1
  fi
  return 0
}

################################################################################
# Function: handle_error
# Description: Centralized error handler
# Parameters:
#   $1 - Error message
#   $2 - Exit code (optional)
# Returns: Never (exits)
################################################################################
handle_error() {
  local message="$1"
  local error_code="${2:-$EXIT_ERROR}"
  
  print_border "ERROR"
  log_and_print "ERROR" "$message" "error"
  log_message "ERROR" "Check log file for details: $logFile"
  echo ""
  echo "Log file: $logFile"
  echo ""
  
  exit "$error_code"
}

################################################################################
# DISPLAY FUNCTIONS
################################################################################

################################################################################
# Function: print_banner
# Description: Display script banner and header
# Parameters: None
# Returns: None
################################################################################
print_banner() {
  clear
  cat <<'EOF'
  __  __                    __
 |  \/  | ___  _ __   ___  / _| ___  _ __
 | |\/| |/ _ \| '_ \ / _ \| |_ / _ \| '__|
 | |  | | (_) | | | | (_) |  _| (_) | |
 |_|  |_|\___/|_| |_|\___/|_|  \___/|_|
EOF
  echo ""
  echo "Monofor Identity Access Management"
  echo "Monofor Privileged Account & Access Management"
  echo "Copyright 2017-$(date +'%Y'), Monofor, Inc."
  echo "https://monofor.com"
  echo "Version: $SCRIPT_VERSION (Build: $SCRIPT_BUILD)"
  print_border ""
}

################################################################################
# Function: print_border
# Description: Print border line with optional title
# Parameters: $1 - Optional title
# Returns: None
################################################################################
print_border() {
  local title="${1:-}"
  local border_length=70
  
  if [[ -z "$title" ]]; then
    printf "%s%s%s\n" "$BLUE" "$(printf '=%.0s' $(seq 1 "$border_length"))" "$RESET"
  else
    printf "%s%s\n" "$BLUE" "$(printf '=%.0s' $(seq 1 "$border_length"))"
    printf "  %s\n" "$title"
    printf "%s%s\n" "$(printf '=%.0s' $(seq 1 "$border_length"))" "$RESET"
  fi
}

################################################################################
# Function: print_section
# Description: Print formatted section header
# Parameters: $1 - Section title
# Returns: None
################################################################################
print_section() {
  local title="$1"
  echo ""
  print_border "$title"
}

################################################################################
# Function: print_step
# Description: Print step with progress indicator
# Parameters:
#   $1 - Current step number
#   $2 - Total steps
#   $3 - Step description
# Returns: None
################################################################################
print_step() {
  local current="$1"
  local total="$2"
  local description="$3"
  local progress=$((current * 100 / total))
  
  printf "\n▶ [%d/%d] %s (progress: %d%%)\n" "$current" "$total" "$description" "$progress"
}

################################################################################
# Function: print_success
# Description: Print success message
# Parameters: $1 - Message text
# Returns: None
################################################################################
print_success() {
  local message="$1"
  log_message "INFO" "$message"
  printf "%s✓ %s%s\n" "$GREEN" "$message" "$RESET"
}

################################################################################
# Function: print_error
# Description: Print error message
# Parameters: $1 - Message text
# Returns: None
################################################################################
print_error() {
  local message="$1"
  log_message "ERROR" "$message"
  printf "%s✗ %s%s\n" "$RED" "$message" "$RESET" >&2
}

################################################################################
# Function: print_table_header
# Description: Print table header with columns
# Parameters: $@ - Column headers
# Returns: None
################################################################################
print_table_header() {
  local -a headers=("$@")
  local format="%-30s | %s\n"
  
  printf "$format" "${headers[0]}" "${headers[1]}"
  printf "%s\n" "$(printf '%.0s-' $(seq 1 40))"
}

################################################################################
# NETWORK FUNCTIONS
################################################################################

################################################################################
# Function: safe_curl
# Description: Execute curl with timeout, retry logic, and error handling
# Parameters:
#   $1 - URL
#   $2 - Optional cURL options
# Returns: cURL output or empty on failure
################################################################################
safe_curl() {
  local url="$1"
  local options="${2:-}"
  local attempt=1
  
  while [[ $attempt -le $CURL_RETRY_COUNT ]]; do
    if curl -s \
    --connect-timeout "$CURL_CONNECT_TIMEOUT" \
    --max-time "$CURL_MAX_TIME_CHECK" \
    $options \
    "$url" 2>/dev/null; then
      return 0
    fi
    
    if [[ $attempt -lt $CURL_RETRY_COUNT ]]; then
      local wait_time=$((2 ** attempt))
      log_message "WARN" "cURL attempt $attempt/$CURL_RETRY_COUNT failed, retrying in ${wait_time}s"
      sleep "$wait_time"
    fi
    
    attempt=$((attempt + 1))
  done
  
  log_message "ERROR" "cURL failed after $CURL_RETRY_COUNT attempts: $url"
  return 1
}

################################################################################
# Function: verify_url_accessible
# Description: Verify URL returns HTTP 200
# Parameters: $1 - URL
# Returns: 0 if accessible, 1 otherwise
################################################################################
verify_url_accessible() {
  local url="$1"
  
  if safe_curl "$url" "--head" | grep -q "200"; then
    return 0
  else
    return 1
  fi
}

################################################################################
# SYSTEM CHECK FUNCTIONS
################################################################################

################################################################################
# Function: get_os_type
# Description: Detect Linux OS type
# Parameters: None
# Returns: "debian", "rhel", or "unknown"
################################################################################
get_os_type() {
  local os_name
  os_name=$(awk '/^NAME=/' /etc/os-release | sed 's/NAME=//' | tr '[:upper:]' '[:lower:]')
  
  if [[ "$os_name" == *"debian"* ]] || [[ "$os_name" == *"ubuntu"* ]]; then
    echo "debian"
    elif [[ "$os_name" == *"red hat"* ]] || [[ "$os_name" == *"centos"* ]]; then
    echo "rhel"
  else
    echo "unknown"
  fi
}

################################################################################
# Function: check_system_info
# Description: Collect and display system information
# Parameters: None
# Returns: None
################################################################################
check_system_info() {
  print_section "System Information"
  
  echo "Operating System:"
  cat /etc/os-release | grep -E "^(NAME|VERSION)="
  echo ""
  
  echo "Hardware Information:"
  local cpu_cores
  cpu_cores=$(grep -c ^processor /proc/cpuinfo)
  printf "  CPU Cores:      %s\n" "$cpu_cores"
  
  local memory_gb
  memory_gb=$(awk '/MemTotal/ {printf "%.2f", $2/1024/1024}' /proc/meminfo)
  printf "  Memory:         %s GB\n" "$memory_gb"
  
  local disk_total
  disk_total=$(df -BG / | awk 'NR==2 {print $2}')
  printf "  Disk Total:     %s\n" "$disk_total"
  
  local disk_available
  disk_available=$(df -BG / | awk 'NR==2 {print $4}')
  printf "  Disk Available: %s\n" "$disk_available"
  
  log_message "INFO" "System Info - CPU: $cpu_cores, Memory: ${memory_gb}GB, Disk: $disk_total (Available: $disk_available)"
}

################################################################################
# Function: check_required_packages
# Description: Check if required OS packages are installed
# Parameters: None
# Returns: 0 if all installed, 1 if any missing
################################################################################
check_required_packages() {
  print_section "Required Software Packages"
  
  local os_type
  os_type=$(get_os_type)
  
  local os_display_name
  os_display_name=$(awk -F= '/^NAME=/ {gsub(/"/, "", $2); print $2}' /etc/os-release)
  local os_version
  os_version=$(grep -E "^VERSION=" /etc/os-release | sed 's/VERSION=//' | tr -d '"')
  
  echo "Your Linux OS is $os_display_name"
  echo "VERSION=$os_version"
  echo ""
  
  local -a packages=()
  
  case "$os_type" in
    debian)
      packages=("docker-ce" "docker-ce-cli" "containerd.io" "docker-buildx-plugin" "docker-compose-plugin" "build-essential" "traceroute" "ethtool" "dnsutils" "open-vm-tools" "net-tools" "tcpdump" "apt-transport-https" "ca-certificates" "curl" "software-properties-common" "unzip" "gnupg" "jq" "bash-completion" "netcat-traditional" "bc" "postgresql-client" "uuid-runtime")
    ;;
    rhel)
      packages=("docker-ce" "docker-ce-cli" "containerd.io" "docker-buildx-plugin" "docker-compose-plugin" "yum-utils" "traceroute" "ethtool" "open-vm-tools" "net-tools" "bind-utils" "epel-release" "tcpdump" "ca-certificates" "curl" "unzip" "gnupg2" "jq" "bash-completion" "netcat" "bc" "postgresql-client")
    ;;
    *)
      print_error "Unsupported OS type: $os_display_name"
      log_message "WARN" "Package check skipped - unsupported OS"
      return 1
    ;;
  esac
  
  printf "%-30s | %s\n" "Package Name" "Status"
  printf "%s|%s\n" "$(printf '%.0s-' $(seq 1 31))" "$(printf '%.0s-' $(seq 1 20))"
  
  local missing=0
  
  for pkg in "${packages[@]}"; do
    local status
    case "$os_type" in
      debian)
        if dpkg-query -W -f='${Status}' "$pkg" 2>/dev/null | grep -q "install ok installed"; then
          status="${GREEN}Installed${RESET}"
        else
          status="${RED}NOT Installed${RESET}"
          missing=1
        fi
      ;;
      rhel)
        if rpm -q "$pkg" &>/dev/null; then
          status="${GREEN}Installed${RESET}"
        else
          status="${RED}NOT Installed${RESET}"
          missing=1
        fi
      ;;
    esac
    printf "%-30s | %s\n" "$pkg" "$status"
    log_message "INFO" "Package check: $pkg - $(echo "$status" | sed 's/\x1b\[[0-9;]*m//g')"
  done
  
  echo ""
  if [[ $missing -eq 1 ]]; then
    print_error "Some required packages are not installed"
    return 1
  else
    print_success "All required packages are installed"
    return 0
  fi
}

################################################################################
# Function: check_firewall_status
# Description: Check firewall status
# Parameters: None
# Returns: None
################################################################################
check_firewall_status() {
  print_section "Firewall Status"
  
  local firewalld_file="/usr/lib/systemd/system/firewalld.service"
  local ufw_file="/lib/systemd/system/ufw.service"
  
  if [[ -e "$firewalld_file" ]]; then
    local fw_status
    fw_status=$(systemctl is-active firewalld 2>/dev/null || echo "inactive")
    printf "  Firewalld:  %s\n" "$fw_status"
    log_message "INFO" "Firewalld status: $fw_status"
    elif [[ -e "$ufw_file" ]]; then
    local ufw_status
    ufw_status=$(systemctl is-active ufw 2>/dev/null || echo "inactive")
    printf "  UFW:        %s\n" "$ufw_status"
    log_message "INFO" "UFW status: $ufw_status"
  else
    print_error "No firewall (firewalld/ufw) found"
    log_message "WARN" "No firewall service found"
  fi
}

################################################################################
# Function: check_dns_resolution
# Description: Check DNS resolution for required services
# Parameters: None
# Returns: None
################################################################################
check_dns_resolution() {
  print_section "DNS Resolution Check"
  
  read -r -p "Please enter Domain Name (Example: monofor.com): " dns_name
  
  if [[ -z "$dns_name" ]]; then
    log_message "WARN" "No domain name provided for DNS check"
    return 1
  fi
  
  local services=("id" "iam" "iam-api" "sync" "pam" "pam-cdn" "pam-cdn-con")
  local missing_dns=0
  
  printf "\n%-25s | %-20s | %s\n" "DNS Name" "Resolution" "FQDN"
  printf "%s\n" "$(printf '%.0s-' {1..70})"
  
  for service in "${services[@]}"; do
    local fqdn="${service}.${dns_name}"
    if nslookup "$fqdn" >/dev/null 2>&1; then
      printf "%-25s | \033[1;32m%-20s\033[0m | %s\n" "$service" "✓ Resolvable" "$fqdn"
      log_message "INFO" "DNS resolved: $fqdn"
    else
      printf "%-25s | \033[1;31m%-20s\033[0m | %s\n" "$service" "✗ Not Resolvable" "$fqdn"
      log_message "WARN" "DNS not resolved: $fqdn"
      missing_dns=1
    fi
  done
  
  if [[ $missing_dns -eq 1 ]]; then
    print_error "Some DNS names are not resolvable"
    return 1
  else
    print_success "All DNS names are resolvable"
    return 0
  fi
}

################################################################################
# Function: check_timezone_ntp
# Description: Check timezone and NTP synchronization
# Parameters: None
# Returns: None
################################################################################
check_timezone_ntp() {
  print_section "Timezone and NTP Status"
  
  if command -v timedatectl &>/dev/null; then
    timedatectl
    log_message "INFO" "Timezone and NTP info collected"
  else
    print_error "timedatectl not found"
    log_message "WARN" "timedatectl command not available"
  fi
}

################################################################################
# Function: comprehensive_pre_check
# Description: Run comprehensive pre-installation checks
# Parameters: None
# Returns: None
################################################################################
comprehensive_pre_check() {
  print_section "Comprehensive Pre-Installation Checks"
  
  local check_log_file="/tmp/monofor-check-$(date +%F).log"
  
  # Initialize log file with header
  {
    echo "============================================================="
    echo "=========Monofor Installation Pre-Requirements Check========="
    echo "Date: $(date)"
    echo "============================================================="
    echo ""
  } > "$check_log_file"
  
  # Run all checks - output to both screen and log file
  # Using || true to prevent non-zero returns from aborting the diagnostic flow
  check_system_info         2>&1 | tee -a "$check_log_file" || true
  check_required_packages   2>&1 | tee -a "$check_log_file" || true
  check_firewall_status     2>&1 | tee -a "$check_log_file" || true
  check_timezone_ntp        2>&1 | tee -a "$check_log_file" || true
  check_docker_access       2>&1 | tee -a "$check_log_file" || true
  check_docker              2>&1 | tee -a "$check_log_file" || true
  check_repo_access         2>&1 | tee -a "$check_log_file" || true
  check_external_services   2>&1 | tee -a "$check_log_file" || true
  check_dns_resolution      2>&1 | tee -a "$check_log_file" || true
  
  # Remove ANSI color codes for plain text log
  sed -i 's/\x1b\[[0-9;]*m//g' "$check_log_file"
  
  log_message "INFO" "Comprehensive pre-check completed"
  log_message "INFO" "Check log saved to: $check_log_file"
}

################################################################################
# Function: check_service_running
# Description: Check if systemd service is running
# Parameters: $1 - Service name
# Returns: 0 if running, 1 otherwise
################################################################################
check_service_running() {
  local service="$1"
  local status
  
  status=$(systemctl is-active "$service" 2>/dev/null || echo "inactive")
  
  if [[ "$status" == "active" ]]; then
    return 0
  else
    return 1
  fi
}

################################################################################
# Function: check_docker
# Description: Verify Docker service is running and display version information
# Parameters: None
# Returns: 0 if running, exits otherwise
################################################################################
check_docker() {
  print_section "Docker Service Check"
  
  if check_service_running "docker"; then
    print_success "Docker service is installed and running"
    log_message "INFO" "Docker service is running"
    
    # Get installed Docker version information
    local docker_client_version=""
    local docker_server_version=""
    
    docker_client_version=$(docker version --format '{{.Client.Version}}' 2>/dev/null || echo "N/A")
    docker_server_version=$(docker version --format '{{.Server.Version}}' 2>/dev/null || echo "N/A")
    
    printf "  Docker Supported Version:  %s29.x.x%s\n" "$BLUE" "$RESET"
    printf "  Docker Client Version:     %s%s%s\n" "$GREEN" "$docker_client_version" "$RESET"
    printf "  Docker Server Version:     %s%s%s\n" "$GREEN" "$docker_server_version" "$RESET"
    
    log_message "INFO" "Docker Client Version: $docker_client_version"
    log_message "INFO" "Docker Server Version: $docker_server_version"
    log_message "INFO" "Docker Supported Version: 29.x.x"
    
    # Get latest official Docker version from download.docker.com
    local docker_latest_version=""
    docker_latest_version=$(curl -s --connect-timeout "$CURL_CONNECT_TIMEOUT" --max-time "$CURL_MAX_TIME_CHECK" \
      "https://download.docker.com/linux/static/stable/x86_64/" 2>/dev/null \
    | grep -oP 'docker-\K[0-9]+\.[0-9]+\.[0-9]+' | sort -V | tail -1)
    
    if [[ -n "$docker_latest_version" ]]; then
      printf "  Docker Latest Version:     %s%s%s (https://download.docker.com)\n" "$YELLOW" "$docker_latest_version" "$RESET"
      log_message "INFO" "Docker Latest Official Version: $docker_latest_version"
      
      if [[ "$docker_client_version" != "N/A" && "$docker_client_version" != "$docker_latest_version" ]]; then
        printf "  %s⚠ Update available: %s → %s%s\n" "$YELLOW" "$docker_client_version" "$docker_latest_version" "$RESET"
        log_message "WARN" "Docker update available: $docker_client_version -> $docker_latest_version"
        elif [[ "$docker_client_version" == "$docker_latest_version" ]]; then
        print_success "Docker is up to date"
        log_message "INFO" "Docker is up to date"
      fi
    else
      printf "  Docker Latest Version:  %sUnable to fetch%s\n" "$RED" "$RESET"
      log_message "WARN" "Could not fetch latest Docker version from download.docker.com"
    fi
    
    return 0
  else
    print_error "Docker service is not running"
    handle_error "Please install Docker before proceeding. See: https://docs.docker.com/engine/install/" "$EXIT_DEPENDENCY_MISSING"
  fi
}

################################################################################
# Function: check_repo_access
# Description: Verify repository access
# Parameters: None
# Returns: 0 if accessible, exits otherwise
################################################################################
check_repo_access() {
  print_section "Monofor Repository Access Check"
  if verify_url_accessible "$REPO_URL"; then
    print_success "Monofor Repository is reachable ($REPO_URL)"
    log_message "INFO" "Monofor Repository access verified: $REPO_URL"
    return 0
  else
    print_error "Monofor Repository is not reachable"
    handle_error "Cannot reach Monofor repository: $REPO_URL. Check network and try again." "$EXIT_NETWORK_ERROR"
  fi
}

################################################################################
# Function: check_docker_access
# Description: Verify Docker repository access
# Parameters: None
# Returns: 0 if accessible, exits otherwise
################################################################################
check_docker_access() {
  print_section "Docker Repository Access Check"
  
  if verify_url_accessible "$DOCKER_URL"; then
    print_success "Docker repository is reachable ($DOCKER_URL)"
    log_message "INFO" "Docker repository access verified: $DOCKER_URL"
    return 0
  else
    print_error "Docker repository is not reachable"
    handle_error "Cannot reach repository: $DOCKER_URL. Check network and try again." "$EXIT_NETWORK_ERROR"
  fi
}

################################################################################
# Function: check_external_services
# Description: Verify external services
# Parameters: None
# Returns: 0 if accessible, exits otherwise
################################################################################
check_external_services() {
  print_section "External Services Check"
  
  local service_status
  service_status=$(safe_curl "$SERVICES_URL/api/v1/ping" | jq -r '.isHealthy // empty' 2>/dev/null || echo "")
  
  if [[ "$service_status" == "true" ]]; then
    print_success "External services are reachable ($SERVICES_URL)"
    log_message "INFO" "External services health check passed"
    return 0
  else
    print_error "External services are not reachable"
    handle_error "Cannot reach external services: $SERVICES_URL" "$EXIT_NETWORK_ERROR"
  fi
}

################################################################################
# INSTALLATION FUNCTIONS
################################################################################

################################################################################
# Function: download_and_extract
# Description: Download and extract installation scripts
# Parameters:
#   $1 - URL to download
#   $2 - Output file
#   $3 - Extract directory
# Returns: 0 on success, 1 on failure
################################################################################
download_and_extract() {
  local url="$1"
  local output_file="$2"
  local extract_dir="$3"
  local http_status
  local temp_header_file="/tmp/monofor-download-header-$$.txt"
  
  # Clean previous attempts
  rm -rf "$extract_dir"
  rm -f "$output_file"
  
  # Download with timeout and capture HTTP status separately
  log_message "INFO" "Downloading from: $url"
  
  http_status=$(curl -sSL \
    --connect-timeout "$CURL_CONNECT_TIMEOUT" \
    --max-time "$CURL_MAX_TIME_DOWNLOAD" \
    -w "%{http_code}" \
    -o "$output_file" \
  "$url" 2>/dev/null)
  
  local curl_exit=$?
  
  # Check curl exit code
  if [[ $curl_exit -ne 0 ]]; then
    log_message "ERROR" "Download failed (curl error): $url (exit code: $curl_exit)"
    rm -f "$output_file" "$temp_header_file"
    return 1
  fi
  
  # Verify HTTP status
  if [[ ! "$http_status" =~ ^20[0-9]$ ]]; then
    log_message "ERROR" "Download returned non-200 status: $url (HTTP $http_status)"
    log_message "WARN" "Response file size: $(stat -f%z "$output_file" 2>/dev/null || echo 'unknown')"
    rm -f "$output_file" "$temp_header_file"
    return 1
  fi
  
  log_message "INFO" "Downloaded successfully (HTTP $http_status): $url"
  
  # Verify file size
  if [[ ! -s "$output_file" ]]; then
    log_message "ERROR" "Downloaded file is empty: $output_file"
    rm -f "$output_file" "$temp_header_file"
    return 1
  fi
  
  # Verify it's a zip file
  if ! file "$output_file" | grep -q "Zip"; then
    log_message "ERROR" "Downloaded file is not a valid ZIP: $output_file"
    log_message "ERROR" "File type: $(file "$output_file")"
    rm -f "$output_file" "$temp_header_file"
    return 1
  fi
  
  # Extract
  log_message "INFO" "Extracting to: $extract_dir"
  mkdir -p "$extract_dir"
  if ! unzip -qq "$output_file" -d "$extract_dir"; then
    log_message "ERROR" "Failed to extract: $output_file"
    rm -f "$output_file" "$temp_header_file"
    return 1
  fi
  
  # Set executable permissions
  chmod +x "$extract_dir"/* 2>/dev/null || true
  
  # Cleanup temp files
  rm -f "$temp_header_file"
  
  log_message "INFO" "Downloaded and extracted successfully: $url"
  return 0
}

################################################################################
# Function: install_scripts
# Description: Download and install main scripts
# Parameters: None
# Returns: 0 on success, exits on failure
################################################################################
install_scripts() {
  local install_url="${baseUrl}/installation.zip"
  local install_zip="/tmp/monofor-installation.zip"
  
  if ! download_and_extract "$install_url" "$install_zip" "$INST_TMP_DIR"; then
    handle_error "Failed to download installation scripts" "$EXIT_ERROR"
  fi
  
  # Copy scripts to /usr/bin
  for script in monofor-build monofor-uninstall monosign monopam monosync; do
    if [[ -f "$INST_TMP_DIR/$script" ]]; then
      cp -p "$INST_TMP_DIR/$script" "$SCRIPT_DIR/$script"
      log_message "INFO" "Installed: $script"
    fi
  done
  
  print_success "Installation scripts installed"
}

################################################################################
# Function: install_tools
# Description: Download and install management tools
# Parameters: None
# Returns: 0 on success, exits on failure
################################################################################
install_tools() {
  local tools_url="${baseUrl}/monofor-tools.zip"
  local tools_zip="/tmp/monofor-tools.zip"
  
  if ! download_and_extract "$tools_url" "$tools_zip" "$TOOLS_TMP_DIR"; then
    handle_error "Failed to download monofor tools" "$EXIT_ERROR"
  fi
  
  # Copy tools to /usr/bin
  cp -p "$TOOLS_TMP_DIR"/* "$SCRIPT_DIR/"
  log_message "INFO" "Monofor tools installed"
  
  print_success "Monofor tools installed"
}

################################################################################
# MENU AND ARGUMENT HANDLING
################################################################################

################################################################################
# Function: show_usage
# Description: Display usage information
# Parameters: None
# Returns: None
################################################################################
show_usage() {
  cat <<EOF

Usage: $SCRIPT_NAME [OPTIONS]

OPTIONS:
  -install              Download and install Monofor scripts
  -check                Run pre-installation checks
  -tools                Download and install Monofor tools
  -v, --version VERSION Install specific script version (default: latest)
  -h, --help            Show this help message

EXAMPLES:
  $SCRIPT_NAME -install
  $SCRIPT_NAME -check
  $SCRIPT_NAME -tools
  $SCRIPT_NAME -v v2025.04
  $SCRIPT_NAME -h

For more information, visit: https://monofor.com

EOF
}

################################################################################
# MAIN EXECUTION
################################################################################

main() {
  check_root
  
  # Display banner
  print_banner
  
  # Check required dependencies
  local required_cmds=("curl" "unzip" "jq" "systemctl" "awk")
  for cmd in "${required_cmds[@]}"; do
    if ! check_dependency "$cmd"; then
      handle_error "Missing required command: $cmd" "$EXIT_DEPENDENCY_MISSING"
    fi
  done
  
  # Parse arguments
  if [[ $# -eq 0 ]]; then
    show_usage
    exit "$EXIT_INVALID_ARGS"
  fi
  
  # Pre-parse version argument first (can appear anywhere)
  local args=("$@")
  local action=""
  local i=0
  
  while [[ $i -lt ${#args[@]} ]]; do
    case "${args[$i]}" in
      -v|--version)
        if [[ $((i + 1)) -lt ${#args[@]} ]]; then
          VERSION="${args[$((i + 1))]}"
          baseUrl="${DOWNLOAD_URL}/install/${VERSION}"
          log_message "INFO" "Using version: $VERSION"
          echo "Version set to: $VERSION"
          i=$((i + 2))
        else
          show_usage
          exit "$EXIT_INVALID_ARGS"
        fi
      ;;
      -install|-check|-tools|-h|--help)
        action="${args[$i]}"
        i=$((i + 1))
      ;;
      *)
        show_usage
        exit "$EXIT_INVALID_ARGS"
      ;;
    esac
  done
  
  # If no action specified, show usage
  if [[ -z "$action" ]]; then
    show_usage
    exit "$EXIT_INVALID_ARGS"
  fi
  
  case "$action" in
    -install)
      print_section "Docker Service Check"
      print_step 1 4 "Checking Docker service"
      check_docker
      
      print_section "Repository Connectivity Check"
      print_step 2 4 "Verifying repository access"
      check_repo_access
      
      print_section "Installing Monofor Scripts"
      print_step 3 4 "Installing scripts"
      install_scripts
      
      print_section "Installing Monofor Tools"
      print_step 4 4 "Installing tools"
      install_tools
      
      print_section "Installation Complete"
      print_success "Monofor installation scripts and tools are ready"
      echo ""
      echo "Next steps:"
      echo "  1. Run: monofor-build"
      echo "  2. Run: monosign"
      echo ""
    ;;
    
    -check)
      comprehensive_pre_check
      
      print_section "Pre-Check Complete"
      print_success "All system checks completed"
      echo ""
      print_success "Check log: /tmp/monofor-check-$(date +%F).log"
      echo ""
      print_success "Please send /tmp/monofor-check-$(date +%F).log to your Sales Engineer if needed."
    ;;
    
    -tools)
      install_tools
    ;;
    
    -h|--help)
      show_usage
    ;;
  esac
  
  exit "$EXIT_SUCCESS"
}

# Execute main function if script is executed directly
main "$@"
