#!/bin/bash

# License Remover Script
# Comprehensive cleanup tool for removing license-related files and cron jobs

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

# Script version
VERSION="1.0"

# Log file
LOG_FILE="/var/log/license_remover_$(date +%Y%m%d_%H%M%S).log"

# Function to display header
show_header() {
    clear
    echo -e "${BLUE}╔════════════════════════════════════════════════════════════╗${NC}"
    echo -e "${BLUE}║         Comprehensive License Remover Script v${VERSION}          ║${NC}"
    echo -e "${BLUE}╚════════════════════════════════════════════════════════════╝${NC}"
    echo ""
}

# Function to log messages
log_message() {
    echo -e "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}

# Function to pause and wait for user input
pause() {
    echo ""
    echo -e "${YELLOW}Press [Enter] key to continue...${NC}"
    read -r fackEnterKey < /dev/tty
}

# Function to remove files/directories safely
safe_remove() {
    if [ -e "$1" ]; then
        rm -rf "$1" 2>/dev/null && log_message "${GREEN}Removed: $1${NC}" || log_message "${RED}Failed to remove: $1${NC}"
    fi
}

# Function to remove cron jobs
remove_cron_job() {
    if [ -f "/etc/cron.d/$1" ]; then
        rm -rf "/etc/cron.d/$1" 2>/dev/null && log_message "${GREEN}Removed cron job: $1${NC}"
    fi
}

# Function to restore chattr attributes and remove
restore_and_remove() {
    if [ -e "$1" ]; then
        chattr -ia "$1" 2>/dev/null
        rm -rf "$1" 2>/dev/null && log_message "${GREEN}Removed (with attribute reset): $1${NC}"
    fi
}

# Function to clean cPanel license files
clean_cpanel() {
    log_message "${YELLOW}Starting cPanel license cleanup...${NC}"
    
    # Restore attributes and remove cPanel license files
    restore_and_remove "/usr/local/cpanel/cpsanitycheck.si"
    restore_and_remove "/usr/local/cpanel/cpane1.lisc"
    restore_and_remove "/usr/local/cpanel/cpkeyclt"
    restore_and_remove "/usr/local/cpanel/cpanel.lisc"
    restore_and_remove "/usr/local/cpanel/cpsrvd_recover"
    restore_and_remove "/usr/local/cpanel/.cpsrvd_back"
    restore_and_remove "/usr/local/cpanel/.cpsrvd_back1"
    restore_and_remove "/usr/local/cpanel/cpanel.lisc2"
    restore_and_remove "/usr/local/cpanel/.cpkeyclt"
    
    # Remove other cPanel related files
    safe_remove "/usr/local/cpanel/cpkeyclt.xz"
    safe_remove "/usr/local/cpanel/cpkeyclt.xz.1"
    safe_remove "/usr/local/cpanel/cpsrvd_rc"
    safe_remove "/usr/local/cpanel/cpanel_rc"
    safe_remove "/usr/local/cpanel/uapi_rc"
    safe_remove "/usr/local/cpanel/whostmgr/bin/whostmgr_rc"
    safe_remove "/usr/local/cpanel/whostmgr/bin/whostmgr10_rc"
    safe_remove "/usr/local/cpanel/whostmgr/bin/xml-api_rc"
    safe_remove "/usr/local/cpanel/cpkeyclt_is_back"
    safe_remove "/usr/local/cpanel/.cpkeyclt_is_back"
    safe_remove "/usr/local/cpanel/cpkeyclt84"
    safe_remove "/usr/local/cpanel/cpkeyclt90"
    safe_remove "/usr/local/cpanel/cpkeyclt849"
    safe_remove "/usr/local/cpanel/cpkeyclt1"
    safe_remove "/usr/local/cpanel/cpkeyclt2"
    safe_remove "/usr/local/cpanel/cpkeyclt_back_2"
    safe_remove "/usr/local/cpanel/cpkeycltorg"
    safe_remove "/usr/local/cpanel/cpsrvd.so2"
    safe_remove "/usr/local/cpanel/cpsrvd."
    safe_remove "/usr/local/cpanel/cpsanitycheck.soasli"
    safe_remove "/usr/local/cpanel/autofixer2"
    safe_remove "/usr/local/cpanel/cpanelbk.lisc"
    safe_remove "/usr/local/cpanel/.isitdeleted"
    safe_remove "/usr/local/cpanel/cpsrvd.tmp"
    safe_remove "/usr/local/cpanel/cpsrvd_recovr"
    safe_remove "/usr/local/cpanel/error_log"
    
    # Remove cPanel related cron jobs
    cron_files=(
        "esp_cpanel" "esp_cpanel_hostname_ssl" "gbcp" "gbcpdownloader" 
        "gbcprunner" "rccp" "rccpdownloader" "rccprunner" "rccpservice"
        "licensecp" "LicenseCP" "CSPcPanel"
    )
    
    for cron in "${cron_files[@]}"; do
        remove_cron_job "$cron"
    done
    
    # Remove cPanel related binaries
    binary_files=(
        "RcCpanelD" "RcCpanelLetsEncrypt" "rccpcontrol" "GbCpanel"
        "gblicensecp" "gblicensecp_run" "gblicensecp_update" "gblicensecp_update_run"
        "gblicensecp_update_v2" "sliupdateCP" "BbtLicenseCP" "XonLicenseCP"
        "RcCpanel" "cpd"
    )
    
    for binary in "${binary_files[@]}"; do
        safe_remove "/usr/bin/$binary"
    done
    
    # Remove cPanel ECP files
    ecp_files=(
        ".ecpcpkeyclt" ".ecpcpanel" ".ecpcpsrvd" ".ecpuapi"
        ".ecpwhostmgr" ".ecpwhostmgr10" ".ecpwhostmgr11" ".ecpwhostmgr12"
        ".ecpwhostmgr13" ".ecpwhostmgr14" ".ecpwhostmgr2" ".ecpwhostmgr4"
        ".ecpwhostmgr5" ".ecpwhostmgr6" ".ecpwhostmgr7" ".ecpwhostmgr9"
        ".ecpxml-api"
    )
    
    for ecp in "${ecp_files[@]}"; do
        safe_remove "/usr/local/cpanel/$ecp"
        safe_remove "/usr/local/cpanel/whostmgr/bin/$ecp"
    done
    
    safe_remove "/usr/local/cpanel/libexec/.ecpcpsrvd-dormant"
    
    # Disable lic sys
    command -v licsys >/dev/null 2>&1 && licsys cpanel disable 2>/dev/null
    safe_remove "/etc/cron.d/licsys_upgrade"
    safe_remove "/usr/bin/licsys"
    
    # Clean postupcp
    if [ -f "/usr/local/cpanel/scripts/postupcp" ]; then
        echo '' > /usr/local/cpanel/scripts/postupcp
    fi
    
    log_message "${GREEN}cPanel license cleanup completed${NC}"
}

# Function to clean LiteSpeed license files
clean_litespeed() {
    log_message "${YELLOW}Starting LiteSpeed license cleanup...${NC}"
    
    # Restore attributes and remove LiteSpeed license files
    restore_and_remove "/usr/local/lsws/conf/trial.key"
    restore_and_remove "/usr/local/lsws/conf/trial.key.old"
    
    # Remove other LiteSpeed related files
    safe_remove "/usr/local/lsws/conf/.last"
    safe_remove "/usr/local/lsws/.ltrc"
    safe_remove "/usr/local/lsws/conf/.ltrc"
    
    # Remove LiteSpeed cron jobs
    cron_files=(
        "lswsv3" "licensels" "licensels8c" "rclsws" "CSPLiteSpeed"
    )
    
    for cron in "${cron_files[@]}"; do
        remove_cron_job "$cron"
    done
    
    # Remove LiteSpeed binaries
    binary_files=(
        "RcLicense_lsws" "RcLicenseLSWS" "RcLicenseLSWS.1" "RcLicenseLSWS.2"
        "RcLicenseLSWS.3" "sliupdateLSWS" "symbol_lsws" "symbolLSWS"
        "AdrinaserverLicenseLSWS" "Rclshttpd" "RcLSWS" "gblicensels"
        "gblicensels_run" "update_lswsv2"
    )
    
    for binary in "${binary_files[@]}"; do
        safe_remove "/usr/bin/$binary"
    done
    
    log_message "${GREEN}LiteSpeed license cleanup completed${NC}"
}

# Function to clean Imunify360 license files
clean_imunify360() {
    log_message "${YELLOW}Starting Imunify360 license cleanup...${NC}"
    
    # Remove Imunify360 files
    safe_remove "/etc/cron.d/esp_imunify360"
    safe_remove "/etc/cron.d/licenseim360"
    safe_remove "/etc/cron.d/rcimunify"
    safe_remove "/etc/cron.d/CSPImunify360"
    
    # Remove Imunify360 binaries
    binary_files=(
        "RcLicenseImunify360" "RcLicenseimunify360" "gblicenseim360"
        "gblicenseim360_run" "sliupdateImunify360"
    )
    
    for binary in "${binary_files[@]}"; do
        safe_remove "/usr/bin/$binary"
    done
    
    log_message "${GREEN}Imunify360 license cleanup completed${NC}"
}

# Function to clean JetBackup license files
clean_jetbackup() {
    log_message "${YELLOW}Starting JetBackup license cleanup...${NC}"
    
    safe_remove "/etc/cron.d/esp_jetbackup"
    safe_remove "/etc/cron.d/rcjetbackup"
    
    binary_files=(
        "RcLicense_jetbackup" "RcLicenseJetBackup" "update_jetbackup"
    )
    
    for binary in "${binary_files[@]}"; do
        safe_remove "/usr/bin/$binary"
    done
    
    log_message "${GREEN}JetBackup license cleanup completed${NC}"
}

# Function to clean CXS license files
clean_cxs() {
    log_message "${YELLOW}Starting CXS license cleanup...${NC}"
    
    safe_remove "/etc/cron.d/licensecx"
    safe_remove "/etc/cron.d/mailcx"
    
    binary_files=(
        "RcLicense_cxs" "RcLicenseCXS" "SetupLicenseCXS" "SetupLicense_cxs"
        "gblicensecx" "gblicensecx_run" "gblicensecx_update" "gblicensecx_update_run"
    )
    
    for binary in "${binary_files[@]}"; do
        safe_remove "/usr/bin/$binary"
    done
    
    log_message "${GREEN}CXS license cleanup completed${NC}"
}

# Function to clean Virtualizor license files
clean_virtualizor() {
    log_message "${YELLOW}Starting Virtualizor license cleanup...${NC}"
    
    restore_and_remove "/usr/local/virtualizor/license2.php"
    safe_remove "/etc/cron.d/rcvirtualizor"
    safe_remove "/usr/bin/RcLicenseVirtualizor"
    safe_remove "/usr/bin/sliupdateVirtualizor"
    
    log_message "${GREEN}Virtualizor license cleanup completed${NC}"
}

# Function to clean DirectAdmin license files
clean_directadmin() {
    log_message "${YELLOW}Starting DirectAdmin license cleanup...${NC}"
    
    safe_remove "/opt/ecp/da"
    safe_remove "/usr/bin/RcDAUpdate"
    safe_remove "/usr/bin/RcLicenseDA"
    safe_remove "/etc/cron.d/rcda"
    safe_remove "/usr/bin/rcdirectadminbackup"
    
    log_message "${GREEN}DirectAdmin license cleanup completed${NC}"
}

# Function to clean Plesk license files
clean_plesk() {
    log_message "${YELLOW}Starting Plesk license cleanup...${NC}"
    
    safe_remove "/usr/bin/RcLicense_plesk"
    safe_remove "/usr/bin/RcLicensePlesk"
    safe_remove "/usr/bin/RcLicense_Plesk"
    safe_remove "/etc/cron.d/rcplesk"
    safe_remove "/etc/cron.d/rcpleskbackup"
    
    log_message "${GREEN}Plesk license cleanup completed${NC}"
}

# Function to clean Softaculous/SitePad license files
clean_softaculous_sitepad() {
    log_message "${YELLOW}Starting Softaculous/SitePad license cleanup...${NC}"
    
    safe_remove "/usr/bin/sliupdateSoftaculous"
    safe_remove "/usr/bin/RcLicenseSoftaculous"
    safe_remove "/etc/cron.d/rcsoftaculous"
    safe_remove "/usr/bin/RcLicenseSitepad"
    safe_remove "/etc/cron.d/rcsitepad"
    safe_remove "/usr/bin/sliupdateSitepad"
    safe_remove "/usr/bin/update_soft"
    
    log_message "${GREEN}Softaculous/SitePad license cleanup completed${NC}"
}

# Function to clean WHMReseller license files
clean_whmreseller() {
    log_message "${YELLOW}Starting WHMReseller license cleanup...${NC}"
    
    safe_remove "/usr/bin/RcLicense_whmreseller"
    safe_remove "/usr/bin/RcLicenseWHMReseller"
    safe_remove "/usr/bin/sliupdateWHMReseller"
    
    log_message "${GREEN}WHMReseller license cleanup completed${NC}"
}

# Function to clean OSM license files
clean_osm() {
    log_message "${YELLOW}Starting OSM license cleanup...${NC}"
    
    safe_remove "/usr/bin/RcLicenseOSM"
    safe_remove "/etc/cron.d/rcosm"
    
    log_message "${GREEN}OSM license cleanup completed${NC}"
}

# Function to clean general license files and cron jobs
clean_general() {
    log_message "${YELLOW}Starting general license cleanup...${NC}"
    
    # Remove general cron jobs
    cron_files=(
        "esp_directadmin" "esp_upgrade" "esp_cln" "licensels8c"
        "esp_upgrade" "helpercln" "mailwhm" "sysmail" "systemmail"
        "wo-com" "licensesc" "licensesc_update" "licensesp"
        "licensesp_updater" "licensesp_update" "licensews"
        "licensewr" "licensejp" "updategb" "licensefssl"
        "LicenseCL" "LicenseIM" "License_LS" "syscare" "syscare_update"
        "syscare_cpanel" "RCclnv2"
    )
    
    for cron in "${cron_files[@]}"; do
        remove_cron_job "$cron"
    done
    
    # Remove general binaries
    binary_files=(
        "esp" "RcCpanelUpdate" "RcLicense_cln" "RcLicenseCLN"
        "RcLicense_cpanel" "rclswscronbackuprclsws" "rccpcontrol"
        "gblicensekc" "gblicensekc_update" "gblicensesc_update.save"
        "installssl" "sliupdateCP" "symbol_cln"
        "symbolCLN" "symbolCP" "RCdaemon" "pid/running.pid"
        "gblicensewr" "gblicensewr_run" "plast" "gbmover" "gbmoverr"
        "gbtmp" "gblicensekc_run" "gblicenseckc_update_run"
        "gblicensews" "gblicensews_run" "olast" "gblicensejp_run"
        "gblicensesp_run" "gblicensesp_update_run" "gbmov1"
        "update_gb" "gblicensefssl" "syspro" "sysconfig"
    )
    
    for binary in "${binary_files[@]}"; do
        safe_remove "/usr/bin/$binary"
    done
    
    # Remove RCBIN directory
    safe_remove "/usr/local/RCBIN"
    
    # Remove root directory files
    root_files=(
        ".gbcx.pid1" ".gbjp.pid1" "gbreq" "proxychains-ng"
        "sourceguardian" "sourceguardian.1" "sourceguardianinstaller"
        "sourceguardianinstaller."* ".backdrive" ".cp.pid1" ".cpver"
        "RCCP.lock" "main_phpD.txt" ".rccp.pid1" "phpD_finder.txt"
        ".cp.result" ".cp.pid" ".back0" ".bash_time"* ".licensestatus"
        ".licensestatus2" "installer" "installer."* "installer_run"
        "testls" "error_log" "ols1clk.sh" "llc" "sonicins.zip"
        "sonicins.phpbk" "installr.sh" ".gbcp.pid" ".gbcp.pid1"
        "RcLicenseCP" "RcLicenseCP.1" "rcreq" ".rnd" "XonLicenseCP"
        "seRcLicense_cpanel" "setup" "cphostname" "autoinstaller"
    )
    
    for file in "${root_files[@]}"; do
        # Use safe_remove with wildcard support
        if [[ "$file" == *"*"* ]]; then
            rm -rf /root/$file 2>/dev/null
        else
            safe_remove "/root/$file"
        fi
    done
    
    # Remove files in /root/fileshost/
    safe_remove "/root/fileshost"
    
    # Remove /usr/local/ directories
    dirs_to_remove=(
        "/usr/local/RC" "/usr/local/RCLSWS" "/usr/local/GB"
        "/usr/local/syscare" "/usr/local/cgls" "/usr/local/.recoverit"
        "/usr/local/.recoverit1" "/usr/local/.recoverit2" "/usr/local/.recoverit3"
        "/usr/local/.vmfi0"
    )
    
    for dir in "${dirs_to_remove[@]}"; do
        safe_remove "$dir"
    done
    
    # Remove /usr/local/RCLSWS.zip
    safe_remove "/usr/local/RCLSWS.zip"
    
    # Remove /opt/ directories
    safe_remove "/opt/license"
    safe_remove "/opt/cpanel/csp"
    
    # Remove /var/lib/ directories
    safe_remove "/var/lib/csp"
    
    # Remove /usr/share/ directories
    safe_remove "/usr/share/installssl.pl"
    safe_remove "/usr/share/goba"
    
    # Remove /etc/ files
    safe_remove "/etc/ld.so.preload"
    safe_remove "/etc/cpupdate.conf"
    
    # Remove systemd services
    safe_remove "/etc/systemd/system/RCLSWS.service"
    safe_remove "/etc/systemd/system/RCCP.service"
    
    # Remove /usr/.rccheck
    safe_remove "/usr/.rccheck"
    
    # Remove CSP files
    safe_remove "/usr/bin/update_cpanelv2"
    safe_remove "/usr/bin/update_cpanelv3"
    safe_remove "/usr/bin/update_imunify"
    safe_remove "/usr/bin/update_jetbackup"
    safe_remove "/usr/bin/update_cloudv2"
    safe_remove "/usr/bin/update_soft"
    safe_remove "/usr/bin/clnupdate"
    safe_remove "/etc/disablecsp"
    
    # Remove run files
    safe_remove "/var/run/update_cpanel"*
    safe_remove "/var/run/clnupdate"*
    safe_remove "/var/run/CSP"*
    
    # Remove CSP binaries
    safe_remove "/usr/bin/CSP"*
    
    # Remove cpsources.conf
    safe_remove "/etc/cpsources.conf"
    
    # Reinstall e2fsprogs
    log_message "Reinstalling e2fsprogs..."
    if command -v yum >/dev/null 2>&1; then
        yum reinstall e2fsprogs -y &>/dev/null
    elif command -v dnf >/dev/null 2>&1; then
        dnf reinstall e2fsprogs -y &>/dev/null
    fi
    
    log_message "${GREEN}General license cleanup completed${NC}"
}

# Function to clean iptables rules
clean_iptables() {
    log_message "${YELLOW}Cleaning iptables rules...${NC}"
    
    # Stop iptables service
    if command -v service >/dev/null 2>&1; then
        service iptables stop &>/dev/null
    fi
    
    # Flush NAT table
    iptables -t nat -F &>/dev/null
    
    # Remove rules blocking cpanel.net
    while IFS= read -r line; do
        rule_num=$(echo "$line" | head -n1 | awk '{print $1}')
        if [[ -n "$rule_num" ]]; then
            iptables -D INPUT "$rule_num" &>/dev/null
            log_message "Removed iptables rule #$rule_num"
        fi
    done < <(iptables --list INPUT --line-number 2>/dev/null | grep -E '*.cpanel.net' || true)
    
    log_message "${GREEN}iptables cleanup completed${NC}"
}

# Function to perform full cleanup
full_cleanup() {
    log_message "${YELLOW}${RED}Starting FULL cleanup...${NC}${NC}"
    
    clean_cpanel
    clean_litespeed
    clean_imunify360
    clean_jetbackup
    clean_cxs
    clean_virtualizor
    clean_directadmin
    clean_plesk
    clean_softaculous_sitepad
    clean_whmreseller
    clean_osm
    clean_general
    clean_iptables
    
    # Restore chattr for cpkeyclt and create empty files
    restore_and_remove "/usr/local/cpanel/cpkeyclt"
    touch /usr/local/cpanel/cpanel.lisc 2>/dev/null
    touch /usr/local/cpanel/cpsanitycheck.so 2>/dev/null
    touch /usr/local/cpanel/cpkeyclt 2>/dev/null
    
    # Run upcp
    log_message "Running /scripts/upcp --force..."
    if [ -f "/scripts/upcp" ]; then
        /scripts/upcp --force &>/dev/null
    fi
    
    # Clear bash history
    > /root/.bash_history 2>/dev/null
    
    log_message "${GREEN}${GREEN}FULL cleanup completed successfully!${NC}${NC}"
}

# Function to display main menu
show_menu() {
    show_header
    echo -e "${CYAN}Main Menu:${NC}"
    echo "1) Full System Cleanup (Complete removal of all license files)"
    echo "2) cPanel License Cleanup"
    echo "3) LiteSpeed License Cleanup"
    echo "4) Imunify360 License Cleanup"
    echo "5) JetBackup License Cleanup"
    echo "6) CXS License Cleanup"
    echo "7) Virtualizor License Cleanup"
    echo "8) DirectAdmin License Cleanup"
    echo "9) Plesk License Cleanup"
    echo "10) Softaculous/SitePad License Cleanup"
    echo "11) WHMReseller License Cleanup"
    echo "12) OSM License Cleanup"
    echo "13) General License Cleanup"
    echo "14) Clean iptables Rules"
    echo "15) View Log"
    echo "16) Exit"
    echo ""
    echo -e "${YELLOW}Log file: $LOG_FILE${NC}"
    echo ""
}

# ULTIMATE FIX: Function to read user choice directly from terminal
read_choice() {
    local choice
    
    while true; do
        # Force read from terminal directly
        echo -n "Enter your choice [1-16]: "
        read -r choice < /dev/tty
        
        # Remove any whitespace
        choice=$(echo "$choice" | tr -d '[:space:]')
        
        # If input is empty, show error and continue
        if [ -z "$choice" ]; then
            echo -e "${RED}Please enter a number between 1 and 16.${NC}"
            continue
        fi
        
        # Validate input is a number
        if ! [[ "$choice" =~ ^[0-9]+$ ]]; then
            echo -e "${RED}Invalid input! Please enter a number only.${NC}"
            continue
        fi
        
        # Validate range
        if [ "$choice" -lt 1 ] || [ "$choice" -gt 16 ]; then
            echo -e "${RED}Invalid option! Please enter a number between 1 and 16.${NC}"
            continue
        fi
        
        # Valid input, break the loop
        break
    done
    
    case $choice in
        1) full_cleanup ;;
        2) clean_cpanel ;;
        3) clean_litespeed ;;
        4) clean_imunify360 ;;
        5) clean_jetbackup ;;
        6) clean_cxs ;;
        7) clean_virtualizor ;;
        8) clean_directadmin ;;
        9) clean_plesk ;;
        10) clean_softaculous_sitepad ;;
        11) clean_whmreseller ;;
        12) clean_osm ;;
        13) clean_general ;;
        14) clean_iptables ;;
        15) view_log ;;
        16) 
            echo -e "${GREEN}Exiting...${NC}"
            exit 0
            ;;
    esac
    
    # Only pause if not exiting
    if [ "$choice" -ne 16 ]; then
        pause
    fi
}

# Function to view log
view_log() {
    if [ -f "$LOG_FILE" ]; then
        if command -v less >/dev/null 2>&1; then
            less "$LOG_FILE"
        else
            cat "$LOG_FILE"
        fi
    else
        echo -e "${RED}Log file not found yet.${NC}"
    fi
}

# Check if running as root
if [ "$EUID" -ne 0 ]; then 
    echo -e "${RED}Please run as root${NC}"
    exit 1
fi

# Main loop
while true
do
    show_menu
    read_choice
done