#!/bin/bash

# AirwavePBX Bootstrap Installer
# Downloads and manages AirwavePBX installations
# Usage: curl -fsSL https://airwavepbx.com/airwavepbx.sh | bash

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# Configuration
VERSIONS_URL="https://versions.airwavepbx.com"
INSTALL_DIR="/tmp/airwavepbx-installer"
AIRWAVE_HOME="/opt/airwavepbx"

# Functions
print_header() {
    echo -e "${CYAN}"
    cat << 'EOF'
                                    ▓▓▓▓▓▓▓▓                                    
                                   ▓▓▓▓▓▓▓▓▓▓                                   
                                  ▓▓▓▓▓▓▓▓▓▓▓▓                                  
                                 ▓▓▓▓▓▓▓▓▓▓▓▓▓▓                                 
                                ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓                                 
                                ▓▓▓▓▓▓▓  ▓▓▓▓▓▓▓   ▓▓▓▓                         
                               ▓▓▓▓▓▓▓    ▓▓▓▓▓  ▓▓▓▓▓▓▓                        
                              ▓▓▓▓▓▓▓     ▓▓▓▓  ▓▓▓▓▓▓▓▓▓                       
                             ▓▓▓▓▓▓▓▓      ▓▓▓ ▓▓▓▓▓▓▓▓▓▓                       
                            ▓▓▓▓▓▓▓▓        ▓  ▓▓▓▓▓▓▓▓▓▓▓                      
                           ▓▓▓▓▓▓▓▓          ▓ ▓▓▓▓▓▓▓▓▓▓▓                      
                           ▓▓▓▓▓▓▓              ▓▓▓▓▓▓▓▓                        
                          ▓▓▓▓▓▓▓               ▓▓▓▓▓▓▓                         
                         ▓▓▓▓▓▓▓▓                ▓▓▓▓▓▓                         
                        ▓▓▓▓▓▓▓▓                 ▓▓▓▓▓▓▓                        
                       ▓▓▓▓▓▓▓▓                   ▓▓▓▓▓▓▓                       
                       ▓▓▓▓▓▓▓      ▓▓▓▓           ▓▓▓▓▓▓▓                      
                      ▓▓▓▓▓▓▓      ▓▓ ▓▓            ▓▓▓▓▓▓▓                     
                     ▓▓▓▓▓▓▓▓     ▓▓▓  ▓▓            ▓▓▓▓▓▓▓▓    ▓              
                    ▓▓▓▓▓▓▓▓      ▓▓   ▓▓             ▓▓▓▓▓▓▓▓▓▓▓▓▓▓            
                   ▓▓▓▓▓▓▓▓▓▓    ▓▓▓    ▓▓   ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓           
                   ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓     ▓▓  ▓▓▓         ▓▓▓▓▓▓▓▓▓▓▓▓▓▓          
                  ▓▓▓▓▓▓▓                ▓▓▓▓▓            ▓▓▓▓▓▓▓▓▓▓▓▓▓         
                 ▓▓▓▓▓▓▓                  ▓▓               ▓▓▓▓▓▓▓▓▓▓▓▓         
                ▓▓▓▓▓▓▓▓                                 ▓    ▓▓▓▓▓▓▓▓          
               ▓▓▓▓▓▓▓▓                                   ▓▓▓                   
               ▓▓▓▓▓▓▓                                     ▓▓▓▓▓▓               
              ▓▓▓▓▓▓▓                                      ▓▓▓▓▓▓▓              
             ▓▓▓▓▓▓▓                                        ▓▓▓▓▓▓▓             
            ▓▓▓▓▓▓▓▓                                         ▓▓▓▓▓▓▓            
           ▓▓▓▓▓▓▓▓                                           ▓▓▓▓▓▓▓           

    ╔══════════════════════════════════════════════════════════════════╗
    ║                    AirwavePBX Bootstrap Installer                ║
    ║                  Download • Verify • Install • Update            ║
    ╚══════════════════════════════════════════════════════════════════╝
EOF
    echo -e "${NC}"
}

print_error() {
    echo -e "${RED}[ERROR] $1${NC}" >&2
}

print_success() {
    echo -e "${GREEN}[SUCCESS] $1${NC}"
}

print_info() {
    echo -e "${BLUE}[INFO] $1${NC}"
}

print_warning() {
    echo -e "${YELLOW}[WARNING] $1${NC}"
}

# Check if running as root
check_root() {
    if [[ $EUID -ne 0 ]]; then
        print_error "This script must be run as root (use sudo)"
        exit 1
    fi
}

# Fetch available versions from server
fetch_versions() {
    print_info "Checking ${VERSIONS_URL} for available versions..."
    
    if ! curl -f -s "${VERSIONS_URL}/" >/dev/null 2>&1; then
        print_warning "Cannot connect to versions server at ${VERSIONS_URL}"
        print_info "Using fallback version list..."
        # Fallback to known versions if server is unreachable
        AVAILABLE_VERSIONS=("1.0.29" "1.0.28" "1.0.27" "1.0.26" "1.0.25" "1.0.24")
        LATEST_VERSION="1.0.29"
        print_success "Using fallback versions (latest: ${LATEST_VERSION})"
        return 0
    fi
    
    AVAILABLE_VERSIONS=($(curl -s "${VERSIONS_URL}/" | \
        grep -oE 'airwavepbx-[0-9]+\.[0-9]+\.[0-9]+\.tar\.gz' | \
        sed 's/airwavepbx-\(.*\)\.tar\.gz/\1/' | \
        sort -V | uniq))
    
    if [[ ${#AVAILABLE_VERSIONS[@]} -eq 0 ]]; then
        print_warning "No versions found on server, using fallback list"
        AVAILABLE_VERSIONS=("1.0.29" "1.0.28" "1.0.27" "1.0.26" "1.0.25" "1.0.24")
        LATEST_VERSION="1.0.29"
        print_success "Using fallback versions (latest: ${LATEST_VERSION})"
        return 0
    fi
    
    LATEST_VERSION="${AVAILABLE_VERSIONS[-1]}"
    print_success "Found ${#AVAILABLE_VERSIONS[@]} available versions (latest: ${LATEST_VERSION})"
}

# Detect current installation
detect_installation() {
    CURRENT_VERSION=""
    INSTALLATION_STATUS=""
    
    if [[ -d "$AIRWAVE_HOME" ]]; then
        # Try to get version from package.json
        if [[ -f "$AIRWAVE_HOME/package.json" ]]; then
            CURRENT_VERSION=$(grep '"version"' "$AIRWAVE_HOME/package.json" | sed 's/.*"version": *"\([^"]*\)".*/\1/' 2>/dev/null)
        fi
        
        # Check service status with timeout
        print_info "Checking service status..."
        if timeout 5 systemctl is-active --quiet airwavepbx 2>/dev/null; then
            INSTALLATION_STATUS="Running"
        elif timeout 5 systemctl is-enabled --quiet airwavepbx 2>/dev/null; then
            INSTALLATION_STATUS="Installed (not running)"
        else
            INSTALLATION_STATUS="Incomplete installation"
        fi
        
        if [[ -n "$CURRENT_VERSION" ]]; then
            print_info "Detected AirwavePBX v${CURRENT_VERSION} (${INSTALLATION_STATUS})"
        else
            print_warning "AirwavePBX installation found but version unknown (${INSTALLATION_STATUS})"
            CURRENT_VERSION="unknown"
        fi
    else
        print_info "No existing AirwavePBX installation detected"
    fi
}

# Compare versions
version_compare() {
    local v1=$1
    local v2=$2
    
    if [[ "$v1" == "$v2" ]]; then
        return 0  # Equal
    elif [[ "$v1" == "unknown" ]]; then
        return 1  # v1 < v2 (unknown is considered older)
    elif echo -e "$v1\n$v2" | sort -V | head -1 | grep -q "^$v1$"; then
        return 1  # v1 < v2
    else
        return 2  # v1 > v2
    fi
}

# Show unified installation menu
show_unified_menu() {
    echo
    print_info "AirwavePBX Installation Manager"
    echo
    
    # Display current installation status
    if [[ -n "$CURRENT_VERSION" && "$CURRENT_VERSION" != "unknown" ]]; then
        print_info "Current Installation: v${CURRENT_VERSION} (${INSTALLATION_STATUS})"
        version_compare "$CURRENT_VERSION" "$LATEST_VERSION"
        local comparison=$?
        
        if [[ $comparison -eq 1 ]]; then
            print_info "Update Available: v${CURRENT_VERSION} → v${LATEST_VERSION}"
        elif [[ $comparison -eq 0 ]]; then
            print_success "You have the latest version installed"
        else
            print_warning "You have a newer version than latest available"
        fi
    elif [[ -n "$CURRENT_VERSION" ]]; then
        print_warning "Existing installation detected but version unknown"
    else
        print_info "No existing installation detected - fresh install available"
    fi
    
    print_info "Latest Available: v${LATEST_VERSION}"
    echo
    
    echo -e "${PURPLE}📋 Available Actions:${NC}"
    local choice_num=1
    
    # Always show fresh install option
    if [[ -n "$CURRENT_VERSION" ]]; then
        echo -e "  ${choice_num}. ${GREEN}🔄 Fresh Install Latest (v${LATEST_VERSION}) - Backup existing${NC}"
    else
        echo -e "  ${choice_num}. ${GREEN}🚀 Fresh Install Latest (v${LATEST_VERSION}) - Recommended${NC}"
    fi
    MENU_OPTIONS[$choice_num]="fresh_latest"
    ((choice_num++))
    
    # Update option (only if existing installation and update available)
    if [[ -n "$CURRENT_VERSION" ]]; then
        version_compare "$CURRENT_VERSION" "$LATEST_VERSION"
        if [[ $? -eq 1 ]]; then
            echo -e "  ${choice_num}. ${CYAN}⬆️  Update to Latest (v${CURRENT_VERSION} → v${LATEST_VERSION})${NC}"
            MENU_OPTIONS[$choice_num]="update_latest"
            ((choice_num++))
        fi
    fi
    
    # Repair option (only if existing installation)
    if [[ -n "$CURRENT_VERSION" ]]; then
        echo -e "  ${choice_num}. ${YELLOW}🔧 Repair Current Installation (v${CURRENT_VERSION})${NC}"
        MENU_OPTIONS[$choice_num]="repair_current"
        ((choice_num++))
    fi
    
    # Select specific version
    echo -e "  ${choice_num}. ${PURPLE}📂 Select Specific Version${NC}"
    MENU_OPTIONS[$choice_num]="select_version"
    ((choice_num++))
    
    # Rollback option (only if backups exist)
    if [[ -n "$CURRENT_VERSION" ]] && list_backups >/dev/null 2>&1; then
        echo -e "  ${choice_num}. ${CYAN}↩️  Rollback to Previous Version${NC}"
        MENU_OPTIONS[$choice_num]="rollback"
        ((choice_num++))
    fi
    
    # System management options (only if installation exists)
    if [[ -n "$CURRENT_VERSION" ]]; then
        echo -e "  ${choice_num}. ${BLUE}⚙️  System Management${NC}"
        MENU_OPTIONS[$choice_num]="system_management"
        ((choice_num++))
    fi
    
    # Exit option
    echo -e "  ${choice_num}. ${RED}❌ Exit${NC}"
    MENU_OPTIONS[$choice_num]="exit"
    MAX_CHOICE=$choice_num
    
    echo
}

# Show version selection submenu
show_version_menu() {
    echo
    echo -e "${PURPLE}📦 Available Versions:${NC}"
    
    local recent_versions=()
    local num_versions=${#AVAILABLE_VERSIONS[@]}
    
    # Get last 5 versions and reverse them (newest first)
    local show_count=5
    if [[ $num_versions -le $show_count ]]; then
        # Reverse all versions
        for ((i=$((num_versions-1)); i>=0; i--)); do
            recent_versions+=("${AVAILABLE_VERSIONS[$i]}")
        done
    else
        # Get last 5 and reverse them
        for ((i=$((num_versions-1)); i>=$((num_versions-show_count)); i--)); do
            recent_versions+=("${AVAILABLE_VERSIONS[$i]}")
        done
    fi
    
    local choice_num=1
    for version in "${recent_versions[@]}"; do
        local marker=""
        if [[ "$version" == "$LATEST_VERSION" ]]; then
            marker=" ${GREEN}(latest, recommended)${NC}"
        elif [[ "$version" == "$CURRENT_VERSION" ]]; then
            marker=" ${YELLOW}(current)${NC}"
        fi
        echo -e "  ${choice_num}. v${version}${marker}"
        VERSION_OPTIONS[$choice_num]="$version"
        ((choice_num++))
    done
    
    if [[ $num_versions -gt $show_count ]]; then
        echo -e "  ${choice_num}. Show more versions"
        VERSION_OPTIONS[$choice_num]="show_more"
        ((choice_num++))
    fi
    
    echo -e "  ${choice_num}. ← Back to main menu"
    VERSION_OPTIONS[$choice_num]="back"
    MAX_VERSION_CHOICE=$choice_num
    echo
}

# List available backups
list_backups() {
    local backup_dirs=($(ls -d /opt/airwavepbx-backup-* 2>/dev/null | sort -r))
    
    if [[ ${#backup_dirs[@]} -eq 0 ]]; then
        return 1
    fi
    
    echo -e "\n${PURPLE}Available backups:${NC}"
    local choice_num=1
    for backup_dir in "${backup_dirs[@]}"; do
        local backup_date=$(basename "$backup_dir" | sed 's/airwavepbx-backup-//')
        local backup_version="unknown"
        
        # Try to get version from backup
        if [[ -f "${backup_dir}/package.json" ]]; then
            backup_version=$(grep '"version"' "${backup_dir}/package.json" | sed 's/.*"version": *"\([^"]*\)".*/\1/' 2>/dev/null)
        fi
        
        echo -e "  ${choice_num}. ${backup_date} (v${backup_version})"
        BACKUP_OPTIONS[$choice_num]="$backup_dir"
        ((choice_num++))
    done
    
    return 0
}

# Show installation options
show_install_options() {
    local selected_version=$1
    
    echo
    echo -e "${PURPLE}Installation options for AirwavePBX v${selected_version}:${NC}"
    
    local option_num=1
    
    if [[ -n "$CURRENT_VERSION" ]]; then
        # Existing installation detected
        version_compare "$CURRENT_VERSION" "$selected_version"
        local comparison=$?
        
        if [[ $comparison -eq 1 ]]; then
            # Current < Selected (upgrade available)
            echo -e "  ${option_num}. ${GREEN}Update from v${CURRENT_VERSION} to v${selected_version} (Recommended)${NC}"
            INSTALL_OPTIONS[$option_num]="update"
            ((option_num++))
        elif [[ $comparison -eq 0 ]]; then
            # Same version
            echo -e "  ${option_num}. Repair current installation (v${selected_version})"
            INSTALL_OPTIONS[$option_num]="repair"
            ((option_num++))
        else
            # Current > Selected (downgrade)
            echo -e "  ${option_num}. ${YELLOW}Downgrade from v${CURRENT_VERSION} to v${selected_version}${NC}"
            INSTALL_OPTIONS[$option_num]="downgrade"
            ((option_num++))
        fi
        
        echo -e "  ${option_num}. Fresh install (backup existing data)"
        INSTALL_OPTIONS[$option_num]="fresh"
        ((option_num++))
        
        echo -e "  ${option_num}. Repair current installation"
        INSTALL_OPTIONS[$option_num]="repair"
        ((option_num++))
        
        # Add rollback option if backups exist
        if list_backups >/dev/null 2>&1; then
            echo -e "  ${option_num}. ${CYAN}Rollback to previous version${NC}"
            INSTALL_OPTIONS[$option_num]="rollback"
            ((option_num++))
        fi
        
    else
        # No existing installation
        echo -e "  ${option_num}. ${GREEN}Fresh installation (Recommended)${NC}"
        INSTALL_OPTIONS[$option_num]="fresh"
        ((option_num++))
    fi
    
    echo -e "  ${option_num}. Show what would be installed (dry run)"
    INSTALL_OPTIONS[$option_num]="dry-run"
    ((option_num++))
    
    echo -e "  ${option_num}. Back to version selection"
    INSTALL_OPTIONS[$option_num]="back"
    ((option_num++))
    
    echo -e "  ${option_num}. Exit"
    INSTALL_OPTIONS[$option_num]="exit"
    echo
}

# Download and verify package
download_package() {
    local version=$1
    local package_name="airwavepbx-${version}"
    
    print_info "Downloading AirwavePBX v${version}..."
    
    # Create temporary directory
    rm -rf "$INSTALL_DIR"
    mkdir -p "$INSTALL_DIR"
    cd "$INSTALL_DIR"
    
    # Download files
    local files=("${package_name}.tar.gz" "${package_name}.tar.gz.sha256" "${package_name}.tar.gz.md5")
    
    for file in "${files[@]}"; do
        print_info "Downloading ${file}..."
        if ! curl -f -L -o "$file" "${VERSIONS_URL}/${file}"; then
            print_error "Failed to download ${file}"
            exit 1
        fi
    done
    
    # Verify checksums
    print_info "Verifying package integrity..."
    
    # Verify SHA256
    local expected_sha256=$(cat "${package_name}.tar.gz.sha256" | awk '{print $1}')
    local actual_sha256=$(sha256sum "${package_name}.tar.gz" | awk '{print $1}')
    
    if [[ "$expected_sha256" != "$actual_sha256" ]]; then
        print_error "SHA256 checksum verification failed!"
        print_error "Expected: $expected_sha256"
        print_error "Actual:   $actual_sha256"
        exit 1
    fi
    
    # Verify MD5
    local expected_md5=$(cat "${package_name}.tar.gz.md5" | awk '{print $1}')
    local actual_md5=$(md5sum "${package_name}.tar.gz" | awk '{print $1}')
    
    if [[ "$expected_md5" != "$actual_md5" ]]; then
        print_error "MD5 checksum verification failed!"
        print_error "Expected: $expected_md5"
        print_error "Actual:   $actual_md5"
        exit 1
    fi
    
    print_success "Package integrity verified"
    
    # Extract package
    print_info "Extracting package..."
    tar -xzf "${package_name}.tar.gz"
    
    if [[ ! -d "$package_name" ]]; then
        print_error "Package extraction failed"
        exit 1
    fi
    
    print_success "Package extracted to ${INSTALL_DIR}/${package_name}"
    EXTRACTED_DIR="${INSTALL_DIR}/${package_name}"
}

# Backup current installation
backup_installation() {
    local backup_dir="/opt/airwavepbx-backup-$(date +%Y%m%d-%H%M%S)"
    
    if [[ -d "$AIRWAVE_HOME" ]]; then
        print_info "Creating backup at ${backup_dir}..."
        cp -r "$AIRWAVE_HOME" "$backup_dir"
        print_success "Backup created: ${backup_dir}"
        echo "$backup_dir" > /tmp/airwave-backup-location
    fi
}

# Restore from backup
restore_from_backup() {
    local backup_location=$1
    
    if [[ -f "/tmp/airwave-backup-location" ]]; then
        backup_location=$(cat /tmp/airwave-backup-location)
    fi
    
    if [[ -z "$backup_location" ]] || [[ ! -d "$backup_location" ]]; then
        print_error "No valid backup location found"
        return 1
    fi
    
    print_info "Restoring from backup: ${backup_location}"
    
    # Stop services
    systemctl stop airwavepbx 2>/dev/null || true
    systemctl stop nginx 2>/dev/null || true
    
    # Remove current installation
    rm -rf "$AIRWAVE_HOME"
    
    # Restore backup
    cp -r "$backup_location" "$AIRWAVE_HOME"
    
    # Restart services
    systemctl start airwavepbx 2>/dev/null || true
    systemctl start nginx 2>/dev/null || true
    
    print_success "System restored from backup"
}

# Update installation preserving data
update_installation() {
    local version=$1
    
    print_info "Performing update to AirwavePBX v${version}..."
    
    # Create backup before update
    backup_installation
    
    # Stop services gracefully
    print_info "Stopping AirwavePBX services..."
    systemctl stop airwavepbx 2>/dev/null || true
    
    # Preserve critical data
    local temp_data="/tmp/airwave-update-data"
    mkdir -p "$temp_data"
    
    if [[ -d "$AIRWAVE_HOME" ]]; then
        # Backup configuration files
        if [[ -f "$AIRWAVE_HOME/config/database.js" ]]; then
            cp "$AIRWAVE_HOME/config/database.js" "$temp_data/"
        fi
        
        # Backup any custom configurations
        if [[ -d "$AIRWAVE_HOME/config" ]]; then
            cp -r "$AIRWAVE_HOME/config" "$temp_data/"
        fi
        
        # Backup user data
        if [[ -d "$AIRWAVE_HOME/uploads" ]]; then
            cp -r "$AIRWAVE_HOME/uploads" "$temp_data/"
        fi
    fi
    
    # Run the installer (it will handle updating)
    cd "$EXTRACTED_DIR"
    chmod +x install.sh
    
    print_info "Running update installation..."
    if ./install.sh --update; then
        # Restore preserved data
        if [[ -d "$temp_data/config" ]]; then
            cp -r "$temp_data/config"/* "$AIRWAVE_HOME/config/" 2>/dev/null || true
        fi
        
        if [[ -d "$temp_data/uploads" ]]; then
            cp -r "$temp_data/uploads" "$AIRWAVE_HOME/" 2>/dev/null || true
        fi
        
        # Clean up temporary data
        rm -rf "$temp_data"
        
        print_success "Update completed successfully!"
        
        # Restart services
        print_info "Restarting services..."
        systemctl restart airwavepbx 2>/dev/null || true
        systemctl restart nginx 2>/dev/null || true
        
        return 0
    else
        print_error "Update failed! Restoring from backup..."
        restore_from_backup
        rm -rf "$temp_data"
        return 1
    fi
}

# Repair installation
repair_installation() {
    local version=$1
    
    print_info "Repairing AirwavePBX v${version} installation..."
    
    # Create backup before repair
    backup_installation
    
    cd "$EXTRACTED_DIR"
    chmod +x install.sh
    
    if ./install.sh --repair; then
        print_success "Repair completed successfully!"
        return 0
    else
        print_error "Repair failed! Restoring from backup..."
        restore_from_backup
        return 1
    fi
}

# Handle rollback to previous version
handle_rollback() {
    declare -A BACKUP_OPTIONS
    
    if ! list_backups; then
        print_error "No backups found for rollback"
        return 1
    fi
    
    local max_backup_choice=${#BACKUP_OPTIONS[@]}
    echo -e "  $((max_backup_choice + 1)). Cancel rollback"
    echo
    
    read -p "Select backup to restore [1]: " backup_choice
    backup_choice=${backup_choice:-1}
    
    if [[ "$backup_choice" == "$((max_backup_choice + 1))" ]]; then
        print_info "Rollback cancelled"
        return 0
    fi
    
    if ! [[ "$backup_choice" =~ ^[0-9]+$ ]] || [[ $backup_choice -lt 1 ]] || [[ $backup_choice -gt $max_backup_choice ]]; then
        print_error "Invalid backup selection"
        return 1
    fi
    
    local selected_backup="${BACKUP_OPTIONS[$backup_choice]}"
    local backup_date=$(basename "$selected_backup" | sed 's/airwavepbx-backup-//')
    
    echo
    print_warning "This will rollback your AirwavePBX installation to backup: ${backup_date}"
    print_warning "Current installation will be backed up before rollback"
    echo
    read -p "Continue with rollback? [y/N]: " confirm
    
    if [[ "$confirm" =~ ^[Yy]$ ]]; then
        print_info "Starting rollback process..."
        
        # Create backup of current state before rollback
        backup_installation
        
        # Perform rollback
        restore_from_backup "$selected_backup"
        
        print_success "Rollback completed successfully!"
        print_info "AirwavePBX has been restored to backup: ${backup_date}"
        
        return 0
    else
        print_info "Rollback cancelled"
        return 0
    fi
}

# Run installation
run_installation() {
    local install_type=$1
    local version=$2
    
    cd "$EXTRACTED_DIR"
    
    # Make install script executable
    chmod +x install.sh
    
    case "$install_type" in
        "fresh")
            print_info "Starting fresh installation of AirwavePBX v${version}..."
            if [[ -n "$CURRENT_VERSION" ]]; then
                backup_installation
            fi
            ./install.sh
            ;;
        "update")
            update_installation "$version"
            return $?
            ;;
        "repair")
            repair_installation "$version"
            return $?
            ;;
        "downgrade")
            print_info "Downgrading to AirwavePBX v${version}..."
            backup_installation
            ./install.sh --force
            ;;
        "rollback")
            # Handle rollback separately
            handle_rollback
            return $?
            ;;
        "dry-run")
            print_info "Dry run - showing package contents..."
            echo "Package contents:"
            ls -la
            echo
            echo "This would run: ./install.sh"
            echo "Installation script help:"
            ./install.sh --help 2>/dev/null || echo "Standard AirwavePBX installation would proceed"
            return
            ;;
    esac
    
    if [[ $? -eq 0 ]]; then
        print_success "Installation completed!"
        
        # Show post-installation information
        echo
        echo -e "${GREEN}╔══════════════════════════════════════════════════════════════════╗${NC}"
        echo -e "${GREEN}║                    🎉 INSTALLATION COMPLETE! 🎉                 ║${NC}"
        echo -e "${GREEN}║                          AirwavePBX                              ║${NC}"
        echo -e "${GREEN}║                Your PBX is Ready for Production                  ║${NC}"
        echo -e "${GREEN}╚══════════════════════════════════════════════════════════════════╝${NC}"
        echo
        echo -e "${RED}╔══════════════════════════════════════════════════════════════════╗${NC}"
        echo -e "${RED}║ IMPORTANT: Reboot your server for a clean startup of all system ║${NC}"
        echo -e "${RED}║            services.                                             ║${NC}"
        echo -e "${RED}╚══════════════════════════════════════════════════════════════════╝${NC}"
        echo
        
        # Clean up backup reference if successful
        rm -f /tmp/airwave-backup-location 2>/dev/null || true
    else
        print_error "Installation failed!"
        return 1
    fi
}

# Main menu loop
# Unified main menu that ALWAYS shows options
unified_main_menu() {
    while true; do
        # Reset arrays
        declare -A MENU_OPTIONS
        declare -A VERSION_OPTIONS
        
        show_unified_menu
        
        read -p "Select option [1]: " main_choice
        main_choice=${main_choice:-1}
        
        if ! [[ "$main_choice" =~ ^[0-9]+$ ]] || [[ $main_choice -lt 1 ]] || [[ $main_choice -gt $MAX_CHOICE ]]; then
            print_error "Invalid choice. Please select 1-${MAX_CHOICE}"
            continue
        fi
        
        local selected_action="${MENU_OPTIONS[$main_choice]}"
        
        case "$selected_action" in
            "fresh_latest")
                download_package "$LATEST_VERSION"
                run_installation "fresh" "$LATEST_VERSION"
                exit 0
                ;;
            "update_latest")
                download_package "$LATEST_VERSION"
                run_installation "update" "$LATEST_VERSION"
                exit 0
                ;;
            "repair_current")
                download_package "$CURRENT_VERSION"
                run_installation "repair" "$CURRENT_VERSION"
                exit 0
                ;;
            "select_version")
                handle_version_selection
                ;;
            "rollback")
                handle_rollback
                continue
                ;;
            "system_management")
                handle_system_management
                continue
                ;;
            "exit")
                print_info "Exiting AirwavePBX installer"
                exit 0
                ;;
            *)
                print_error "Unknown action: $selected_action"
                continue
                ;;
        esac
    done
}

# Handle version selection submenu
handle_version_selection() {
    while true; do
        declare -A VERSION_OPTIONS
        show_version_menu
        
        read -p "Select version [1]: " version_choice
        version_choice=${version_choice:-1}
        
        if ! [[ "$version_choice" =~ ^[0-9]+$ ]] || [[ $version_choice -lt 1 ]] || [[ $version_choice -gt $MAX_VERSION_CHOICE ]]; then
            print_error "Invalid choice. Please select 1-${MAX_VERSION_CHOICE}"
            continue
        fi
        
        local selected_option="${VERSION_OPTIONS[$version_choice]}"
        
        case "$selected_option" in
            "show_more")
                show_all_versions
                continue
                ;;
            "back")
                return 0
                ;;
            *)
                # Selected a specific version
                handle_version_action "$selected_option"
                return 0
                ;;
        esac
    done
}

# Show all available versions
show_all_versions() {
    echo -e "\n${PURPLE}📦 All Available Versions (newest first):${NC}"
    local choice_counter=1
    for ((i=$((${#AVAILABLE_VERSIONS[@]}-1)); i>=0; i--)); do
        local version="${AVAILABLE_VERSIONS[$i]}"
        local marker=""
        if [[ "$version" == "$LATEST_VERSION" ]]; then
            marker=" ${GREEN}(latest, recommended)${NC}"
        elif [[ "$version" == "$CURRENT_VERSION" ]]; then
            marker=" ${YELLOW}(current)${NC}"
        fi
        echo -e "  ${choice_counter}. v${version}${marker}"
        ((choice_counter++))
    done
    echo
    
    read -p "Select version [1]: " all_version_choice
    all_version_choice=${all_version_choice:-1}
    
    if [[ "$all_version_choice" =~ ^[0-9]+$ ]] && [[ $all_version_choice -ge 1 ]] && [[ $all_version_choice -le ${#AVAILABLE_VERSIONS[@]} ]]; then
        local version_index=$((${#AVAILABLE_VERSIONS[@]} - all_version_choice))
        local selected_version="${AVAILABLE_VERSIONS[$version_index]}"
        handle_version_action "$selected_version"
    else
        print_error "Invalid choice"
    fi
}

# Handle action for a selected version
handle_version_action() {
    local selected_version=$1
    
    echo
    print_info "Selected: AirwavePBX v${selected_version}"
    echo
    echo -e "${PURPLE}🎯 Installation Options:${NC}"
    
    local option_num=1
    declare -A ACTION_OPTIONS
    
    if [[ -n "$CURRENT_VERSION" ]]; then
        version_compare "$CURRENT_VERSION" "$selected_version"
        local comparison=$?
        
        if [[ $comparison -eq 1 ]]; then
            echo -e "  ${option_num}. ${GREEN}⬆️  Update from v${CURRENT_VERSION} to v${selected_version}${NC}"
            ACTION_OPTIONS[$option_num]="update"
        elif [[ $comparison -eq 0 ]]; then
            echo -e "  ${option_num}. ${YELLOW}🔧 Repair current installation (v${selected_version})${NC}"
            ACTION_OPTIONS[$option_num]="repair"
        else
            echo -e "  ${option_num}. ${YELLOW}⬇️  Downgrade from v${CURRENT_VERSION} to v${selected_version}${NC}"
            ACTION_OPTIONS[$option_num]="downgrade"
        fi
        ((option_num++))
        
        echo -e "  ${option_num}. ${GREEN}🔄 Fresh install (backup existing)${NC}"
        ACTION_OPTIONS[$option_num]="fresh"
        ((option_num++))
    else
        echo -e "  ${option_num}. ${GREEN}🚀 Fresh installation${NC}"
        ACTION_OPTIONS[$option_num]="fresh"
        ((option_num++))
    fi
    
    echo -e "  ${option_num}. ${RED}← Back to version selection${NC}"
    ACTION_OPTIONS[$option_num]="back"
    local max_action_choice=$option_num
    
    echo
    read -p "Select installation option [1]: " action_choice
    action_choice=${action_choice:-1}
    
    if ! [[ "$action_choice" =~ ^[0-9]+$ ]] || [[ $action_choice -lt 1 ]] || [[ $action_choice -gt $max_action_choice ]]; then
        print_error "Invalid choice. Please select 1-${max_action_choice}"
        return 1
    fi
    
    local selected_action="${ACTION_OPTIONS[$action_choice]}"
    
    case "$selected_action" in
        "back")
            return 1
            ;;
        *)
            download_package "$selected_version"
            run_installation "$selected_action" "$selected_version"
            exit 0
            ;;
    esac
}

# Handle system management options
handle_system_management() {
    echo
    echo -e "${PURPLE}⚙️  System Management:${NC}"
    echo -e "  1. ${BLUE}🔄 Restart AirwavePBX Services${NC}"
    echo -e "  2. ${BLUE}📊 Check System Status${NC}"
    echo -e "  3. ${BLUE}🔍 View System Logs${NC}"
    echo -e "  4. ${YELLOW}🛠️  Advanced Options${NC}"
    echo -e "  5. ${RED}← Back to main menu${NC}"
    echo
    
    read -p "Select option [1]: " mgmt_choice
    mgmt_choice=${mgmt_choice:-1}
    
    case $mgmt_choice in
        1)
            print_info "Restarting AirwavePBX services..."
            systemctl restart airwavepbx asterisk
            print_success "Services restarted"
            ;;
        2)
            print_info "System Status:"
            systemctl status airwavepbx asterisk --no-pager
            ;;
        3)
            print_info "Recent AirwavePBX logs:"
            journalctl -u airwavepbx --no-pager -n 20
            ;;
        4)
            print_info "Advanced system management options would be shown here"
            ;;
        5)
            return 0
            ;;
        *)
            print_error "Invalid choice"
            ;;
    esac
    
    echo
    read -p "Press Enter to continue..."
}

# Legacy main_menu function for compatibility
main_menu() {
    unified_main_menu
}

# Check if script is being piped from curl
is_piped_from_curl() {
    # Check if stdin is not a terminal AND we don't have a source file
    [[ ! -t 0 ]] && [[ -z "${BASH_SOURCE[0]}" || "${BASH_SOURCE[0]}" == "bash" ]]
}

# Handle piped execution (curl | bash)
handle_piped_execution() {
    print_header
    
    check_root
    fetch_versions
    detect_installation
    
    echo
    print_info "Latest available version: ${LATEST_VERSION}"
    
    if [[ -n "$CURRENT_VERSION" ]]; then
        version_compare "$CURRENT_VERSION" "$LATEST_VERSION"
        case $? in
            0)
                print_success "You have the latest version installed (${CURRENT_VERSION})"
                print_info "Nothing to do!"
                exit 0
                ;;
            1)
                print_info "Update available: ${CURRENT_VERSION} → ${LATEST_VERSION}"
                print_info "Automatically downloading and installing latest version..."
                ;;
            2)
                print_warning "You have a newer version than available (${CURRENT_VERSION} > ${LATEST_VERSION})"
                print_info "Using latest available version: ${LATEST_VERSION}"
                ;;
        esac
    else
        print_info "No existing installation detected"
        print_info "Installing latest version: ${LATEST_VERSION}"
    fi
    
    # Auto-install latest version
    download_package "$LATEST_VERSION"
    run_installation "fresh" "$LATEST_VERSION"
}

# Quick update function
quick_update() {
    print_header
    check_root
    fetch_versions
    detect_installation
    
    if [[ -z "$CURRENT_VERSION" ]]; then
        print_error "No existing AirwavePBX installation found"
        print_info "Use: $0 --install for fresh installation"
        exit 1
    fi
    
    version_compare "$CURRENT_VERSION" "$LATEST_VERSION"
    case $? in
        0)
            print_success "You already have the latest version installed (${CURRENT_VERSION})"
            exit 0
            ;;
        1)
            print_info "Update available: ${CURRENT_VERSION} → ${LATEST_VERSION}"
            ;;
        2)
            print_warning "You have a newer version than available (${CURRENT_VERSION} > ${LATEST_VERSION})"
            print_info "Using latest available version: ${LATEST_VERSION}"
            ;;
    esac
    
    echo
    print_warning "This will update AirwavePBX from v${CURRENT_VERSION} to v${LATEST_VERSION}"
    read -p "Continue with update? [y/N]: " confirm
    
    if [[ "$confirm" =~ ^[Yy]$ ]]; then
        download_package "$LATEST_VERSION"
        run_installation "update" "$LATEST_VERSION"
    else
        print_info "Update cancelled"
        exit 0
    fi
}

# Show usage information
show_usage() {
    echo "AirwavePBX Bootstrap Installer"
    echo "Usage: $0 [OPTIONS]"
    echo
    echo "Options:"
    echo "  --update     Quickly update to latest version"
    echo "  --install    Fresh installation (interactive menu)"
    echo "  --help       Show this help message"
    echo
    echo "Examples:"
    echo "  $0                # Interactive menu"
    echo "  $0 --update       # Quick update to latest"
    echo "  curl -fsSL https://airwavepbx.com/airwavepbx.sh | bash  # Auto-install latest"
}

# Main execution - ALWAYS shows unified menu
main() {
    # Handle command line arguments
    case "${1:-}" in
        "--update")
            quick_update
            exit 0
            ;;
        "--install"|"")
            # Continue to unified menu
            ;;
        "--help"|"-h")
            show_usage
            exit 0
            ;;
        *)
            print_error "Unknown option: $1"
            show_usage
            exit 1
            ;;
    esac
    
    # Check if being piped from curl
    if is_piped_from_curl; then
        handle_piped_execution
        exit 0
    fi
    
    print_header
    check_root
    fetch_versions
    detect_installation
    
    # ALWAYS show the unified menu regardless of installation status
    unified_main_menu
}

# Cleanup on exit
cleanup() {
    if [[ -d "$INSTALL_DIR" ]]; then
        rm -rf "$INSTALL_DIR"
    fi
}

trap cleanup EXIT

# Run main function
main "$@"