#!/usr/bin/env bash
# ========================================
# TuxTuner - Enterprise Linux Optimization Tool
# Version: 2.1
# Koosha Yeganeh - 2025
# ========================================

set -euo pipefail

# Configuration
LOG_FILE="/tmp/tuxtuner.log"
TMP_DIR="/tmp/tuxtuner_$(date +%Y%m%d_%H%M%S)"
DIALOG_BACKTITLE="TuxTuner v1.0 - Enterprise Linux Optimization"
DISTRO=""
DISTRO_VERSION=""

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

# Initialize logging
init_logging() {
    mkdir -p "$(dirname "$LOG_FILE")"
    touch "$LOG_FILE"
    exec > >(tee -a "$LOG_FILE") 2>&1
    echo -e "\n=== TuxTuner started at $(date) ===" >> "$LOG_FILE"
    log_info "Logging initialized at $LOG_FILE"
}

# Logging functions
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
    echo "[INFO] $(date '+%Y-%m-%d %H:%M:%S') - $1" >> "$LOG_FILE"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
    echo "[SUCCESS] $(date '+%Y-%m-%d %H:%M:%S') - $1" >> "$LOG_FILE"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
    echo "[WARNING] $(date '+%Y-%m-%d %H:%M:%S') - $1" >> "$LOG_FILE"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
    echo "[ERROR] $(date '+%Y-%m-%d %H:%M:%S') - $1" >> "$LOG_FILE"
}

# Initialize temporary directory
init_temp_dir() {
    mkdir -p "$TMP_DIR"
    trap 'cleanup' EXIT INT TERM
    log_info "Temporary directory created at $TMP_DIR"
}

# Cleanup function
cleanup() {
    if [ -d "$TMP_DIR" ]; then
        rm -rf "$TMP_DIR"
        log_info "Temporary files cleaned up"
    fi
}

# Check root privileges
check_root() {
    if [ "$(id -u)" -ne 0 ]; then
        log_error "This script must be run as root. Use sudo."
        exit 1
    fi
    log_info "Running with root privileges"
}

# Detect the Linux distribution and version
detect_distro() {
    if [ -f /etc/os-release ]; then
        . /etc/os-release
        DISTRO=$ID
        DISTRO_VERSION=$VERSION_ID
    elif [ -f /etc/redhat-release ]; then
        DISTRO="rhel"
        DISTRO_VERSION=$(grep -oE '[0-9]+\.[0-9]+' /etc/redhat-release)
    elif [ -f /etc/debian_version ]; then
        DISTRO="debian"
        DISTRO_VERSION=$(cat /etc/debian_version)
    else
        DISTRO=$(uname -s | tr '[:upper:]' '[:lower:]')
    fi

    # Additional detection for specific distributions
    case $DISTRO in
        ubuntu|debian|fedora|centos|rhel|opensuse|sles|arch|alpine)
            ;;
        *)
            if [ -f /etc/lsb-release ]; then
                . /etc/lsb-release
                DISTRO=$DISTRIB_ID
                DISTRO_VERSION=$DISTRIB_RELEASE
            fi
            ;;
    esac

    log_info "Detected distribution: $DISTRO $DISTRO_VERSION"
}

# Check if dialog is installed
check_dialog() {
    if ! command -v dialog >/dev/null 2>&1; then
        log_warning "Dialog not found. Attempting to install..."
        
        case $DISTRO in
            ubuntu|debian)
                apt-get update && apt-get install -y dialog
                ;;
            centos|rhel|fedora)
                yum install -y dialog
                ;;
            opensuse*|sles)
                zypper install -y dialog
                ;;
            arch)
                pacman -Sy --noconfirm dialog
                ;;
            alpine)
                apk add dialog
                ;;
            *)
                log_error "Unable to install dialog automatically for $DISTRO"
                return 1
                ;;
        esac
        
        if ! command -v dialog >/dev/null 2>&1; then
            log_error "Dialog installation failed. Falling back to CLI mode."
            return 1
        fi
    fi
    return 0
}

# Display main menu
show_main_menu() {
    while true; do
        choice=$(dialog --backtitle "$DIALOG_BACKTITLE" \
                        --title "Main Menu" \
                        --menu "Choose an optimization profile:" 20 70 13 \
                        1 "Desktop Optimization" \
                        2 "Server Optimization" \
                        3 "Enterprise Optimizations" \
                        4 "Distribution-specific Desktop" \
                        5 "Embedded Systems" \
                        6 "View Logs" \
                        7 "System Information" \
                        8 "Help" \
                        0 "Exit" \
                        3>&1 1>&2 2>&3)
        
        case $choice in
            1) show_desktop_menu ;;
            2) show_server_menu ;;
            3) show_enterprise_menu ;;
            4) show_distro_menu ;;
            5) run_optimization "--embedded" ;;
            6) show_logs ;;
            7) show_system_info ;;
            8) show_help_menu ;;
            0) break ;;
            *) break ;;
        esac
    done
}

# [Rest of your menu functions (show_desktop_menu, show_server_menu, etc.)]

# Display help information
show_help() {
    echo -e "${CYAN}TuxTuner - Enterprise Linux Optimization Tool${NC}"
    echo -e "${BLUE}Version: 1.0${NC}"
    echo ""
    echo -e "${GREEN}Usage:${NC} $0 [OPTIONS] or run without arguments for interactive mode"
    echo ""
    echo -e "${YELLOW}Main Options:${NC}"
    echo "  --desktop --storage       Optimize for desktop as storage server"
    echo "  --desktop --mediaserver   Optimize for desktop as media server"
    echo "  --server --storageserver  Optimize for server as storage server"
    echo "  --server --mediaserver    Optimize for server as media server"
    echo "  --server --idsips         Optimize for server as IDS/IPS"
    echo "  --embedded                Optimize for embedded devices"
    echo ""
    echo -e "${YELLOW}Distribution-specific:${NC}"
    echo "  --ubuntu-desktop          Optimize Ubuntu desktop"
    echo "  --debian-desktop          Optimize Debian desktop"
    echo "  --fedora-desktop          Optimize Fedora desktop"
    echo "  --centos-desktop          Optimize CentOS desktop"
    echo "  --opensuse-desktop        Optimize openSUSE desktop"
    echo "  --arch-desktop            Optimize Arch Linux desktop"
    echo ""
    echo -e "${YELLOW}Enterprise Optimizations:${NC}"
    echo "  --enterprise-kernel       Apply enterprise kernel tuning"
    echo "  --enterprise-services     Optimize enterprise services"
    echo "  --enterprise-security     Apply enterprise security hardening"
    echo "  --enterprise-all          Apply all enterprise optimizations"
    echo ""
    echo -e "${YELLOW}Information:${NC}"
    echo "  --help                    Show this help message"
    echo "  --version                 Show version information"
    echo "  --info                    Show system information"
    echo ""
    echo -e "${GREEN}Examples:${NC}"
    echo "  $0 --ubuntu-desktop --enterprise-security"
    echo "  $0 --server --storageserver --enterprise-kernel"
    echo "  sudo $0 --enterprise-all"
}

# [All your original optimization functions (enterprise_kernel_tuning, etc.)]

# Main execution logic
main() {
    # Parse command line arguments
    while [[ $# -gt 0 ]]; do
        case "$1" in
            --help)
                show_help
                exit 0
                ;;
            --version)
                echo "TuxTuner v2.1"
                exit 0
                ;;
            --info)
                detect_distro
                show_system_info
                exit 0
                ;;
            *)
                # Process other arguments
                shift
                ;;
        esac
    done

    # Initialize
    init_logging
    init_temp_dir
    detect_distro

    # Check if running in interactive mode
    if [ $# -eq 0 ]; then
        if check_dialog; then
            show_main_menu
        else
            log_error "Unable to start interactive mode. Use command-line options instead."
            show_help
            exit 1
        fi
    else
        # Non-interactive mode
        log_info "Running with arguments: $*"
        check_root
        
        # Here you would process the command-line arguments
        # and call the appropriate optimization functions
        # For example:
        # if [[ "$*" == *"--enterprise-kernel"* ]]; then
        #     enterprise_kernel_tuning
        # fi
    fi

    log_success "TuxTuner operations completed successfully"
    echo -e "${GREEN}Optimization complete!${NC}"
    echo -e "Check ${CYAN}$LOG_FILE${NC} for details."
}

# Start the script
main "$@"

exit 0
