
#!/bin/bash
#====================================================
# ATP Hosting 24 - cPanel License Update Script
# /usr/bin/update_cpanelv2
# Domain: atphosting24.com
#====================================================

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m'

SCRIPT_URL="https://script.atphosting24.com"
CPANEL_LICENSE_DIR="/usr/local/cpanel/cpanel_lsel"
INSTALL_DIR="/usr/local/src/atphosting24"
LOG_FILE="/var/log/atphosting24_license.log"

# Print banner
print_banner() {
    echo -e "${CYAN}"
    echo "╔══════════════════════════════════════════════════════════╗"
    echo "║          ATP Hosting 24 - License Manager               ║"
    echo "║              script.atphosting24.com                    ║"
    echo "╚══════════════════════════════════════════════════════════╝"
    echo -e "${NC}"
}

log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

log_step() {
    echo -e "${BLUE}[STEP]${NC} $1"
}

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

# Uninstall the licensing system
uninstall_license() {
    print_banner
    echo -e "${YELLOW}"
    echo "  *** Uninstalling ATP Hosting 24 cPanel Licensing System ***"
    echo -e "${NC}"

    log_step "Removing license files..."

    # Remove license directory
    if [[ -d "$CPANEL_LICENSE_DIR" ]]; then
        rm -rf "$CPANEL_LICENSE_DIR"
        log_info "Removed: $CPANEL_LICENSE_DIR"
    fi

    # Remove install directory
    if [[ -d "$INSTALL_DIR" ]]; then
        rm -rf "$INSTALL_DIR"
        log_info "Removed: $INSTALL_DIR"
    fi

    # Remove log file
    if [[ -f "$LOG_FILE" ]]; then
        rm -f "$LOG_FILE"
        log_info "Removed: $LOG_FILE"
    fi

    # Remove cron job
    log_step "Removing cron jobs..."
    crontab -l 2>/dev/null | grep -v "update_cpanelv2" | grep -v "atphosting24" | crontab -
    log_info "Cron jobs removed"

    # Remove systemd timer if exists
    if [[ -f /etc/systemd/system/atphosting24-license.timer ]]; then
        systemctl stop atphosting24-license.timer 2>/dev/null
        systemctl disable atphosting24-license.timer 2>/dev/null
        rm -f /etc/systemd/system/atphosting24-license.timer
        rm -f /etc/systemd/system/atphosting24-license.service
        systemctl daemon-reload
        log_info "Systemd timer removed"
    fi

    # Restore original cPanel files if backed up
    log_step "Restoring original cPanel files..."
    for file in /usr/local/cpanel/cpanel /usr/local/cpanel/bin/check_cpanel_lp /usr/local/cpanel/whostmgr/bin/licensecheck; do
        if [[ -f "${file}.orig_atphosting24" ]]; then
            mv "${file}.orig_atphosting24" "$file"
            log_info "Restored: $file"
        fi
    done

    # Restart cPanel services
    log_step "Restarting cPanel services..."
    /usr/local/cpanel/cpanel -restart 2>/dev/null || systemctl restart cpanel 2>/dev/null || true

    # Remove this script itself
    log_step "Removing update script..."
    rm -f /usr/bin/update_cpanelv2

    echo ""
    echo -e "${GREEN}═════════════════════════════════════════════════════════════${NC}"
    echo -e "${GREEN}  ATP Hosting 24 Licensing System has been uninstalled.${NC}"
    echo -e "${GREEN}═════════════════════════════════════════════════════════════${NC}"
}

# Install SSL for hostname
install_ssl() {
    print_banner
    echo -e "${CYAN}"
    echo "  *** Installing SSL for Hostname ***"
    echo -e "${NC}"

    # Get hostname
    HOSTNAME_FQDN=$(hostname -f 2>/dev/null || hostname)
    log_info "Hostname: $HOSTNAME_FQDN"

    # Check if cPanel is installed
    if [[ ! -d /usr/local/cpanel ]]; then
        log_error "cPanel is not installed"
        exit 1
    fi

    # Method 1: Use cPanel AutoSSL
    log_step "Checking AutoSSL availability..."
    if [[ -f /usr/local/cpanel/bin/autossl_check ]]; then
        log_info "Running AutoSSL check..."
        /usr/local/cpanel/bin/autossl_check --all 2>/dev/null
    fi

    # Method 2: Use cPanel SSL management
    log_step "Generating SSL certificate..."
    if [[ -f /usr/local/cpanel/bin/cpkeyclt ]]; then
        log_info "Running cpkeyclt..."
        /usr/local/cpanel/bin/cpkeyclt 2>/dev/null
    fi

    # Method 3: Generate self-signed certificate if no other method works
    if [[ ! -f /var/cpanel/ssl/cpanel/cpanel.pem ]] && [[ ! -f /var/cpanel/ssl/cpanel/mycpanel.pem ]]; then
        log_step "Generating self-signed SSL certificate..."

        SSL_DIR="/var/cpanel/ssl/cpanel"
        mkdir -p "$SSL_DIR"

        # Generate key and certificate
        openssl req -x509 -newkey rsa:2048 -keyout "$SSL_DIR/mycpanel.key" \
            -out "$SSL_DIR/mycpanel.pem" \
            -days 3650 -nodes \
            -subj "/C=US/ST=State/L=City/O=ATP Hosting 24/CN=$HOSTNAME_FQDN" 2>/dev/null

        if [[ -f "$SSL_DIR/mycpanel.pem" ]]; then
            # Combine key and cert
            cat "$SSL_DIR/mycpanel.key" "$SSL_DIR/mycpanel.pem" > "$SSL_DIR/cpanel.pem"
            chmod 600 "$SSL_DIR/cpanel.pem"
            chmod 600 "$SSL_DIR/mycpanel.key"
            log_info "Self-signed SSL certificate generated"
        fi
    fi

    # Method 4: Try Let's Encrypt via cPanel
    log_step "Checking Let's Encrypt..."
    if [[ -f /usr/local/cpanel/3rdparty/bin/certbot ]]; then
        log_info "Attempting Let's Encrypt certificate..."
        /usr/local/cpanel/3rdparty/bin/certbot certonly --standalone -d "$HOSTNAME_FQDN" --non-interactive --agree-tos --email admin@"$HOSTNAME_FQDN" 2>/dev/null || true
    fi

    # Restart cPanel services to apply SSL
    log_step "Restarting cPanel services..."

    # Restart all cPanel services
    /usr/local/cpanel/cpanel -restart 2>/dev/null || true
    systemctl restart cpanel 2>/dev/null || true
    systemctl restart cpanel-dovecot 2>/dev/null || true
    systemctl restart cpanel-exim 2>/dev/null || true
    systemctl restart cpanel-httpd 2>/dev/null || true

    # Verify SSL
    if [[ -f /var/cpanel/ssl/cpanel/cpanel.pem ]]; then
        log_info "SSL certificate is in place"
        echo ""
        openssl x509 -in /var/cpanel/ssl/cpanel/cpanel.pem -noout -subject -dates 2>/dev/null || true
    fi

    echo ""
    echo -e "${GREEN}═════════════════════════════════════════════════════════════${NC}"
    echo -e "${GREEN}  SSL installation completed for: $HOSTNAME_FQDN${NC}"
    echo -e "${GREEN}═════════════════════════════════════════════════════════════${NC}"
}

# Update the licensing system
update_license() {
    print_banner
    echo -e "${CYAN}"
    echo "  *** Updating ATP Hosting 24 cPanel Licensing System ***"
    echo -e "${NC}"

    local TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')
    echo "$TIMESTAMP - Starting license update..." >> "$LOG_FILE"

    # Check if cPanel is installed
    if [[ ! -d /usr/local/cpanel ]]; then
        log_error "cPanel is not installed"
        exit 1
    fi

    # Step 1: Ensure license directory exists
    log_step "Verifying license directory..."
    mkdir -p "$CPANEL_LICENSE_DIR"

    # Step 2: Update license file
    log_step "Updating license file..."
    cat > "$CPANEL_LICENSE_DIR/license" << LICENSEEOF
# ATP Hosting 24 - cPanel License
# Licensed via script.atphosting24.com
LICENSE_TYPE=internal
LICENSE_STATUS=active
LICENSE_KEY=ATPHOSTING24-CPANEL-INTERNAL
LICENSE_ISSUED=$(date +%Y-%m-%d)
LICENSE_EXPIRES=2099-12-31
LICENSE_SERVER=script.atphosting24.com
LICENSEEOF

    chmod 600 "$CPANEL_LICENSE_DIR/license"
    chown root:root "$CPANEL_LICENSE_DIR/license"
    log_info "License file updated"

    # Step 3: Update config file
    log_step "Updating configuration..."
    cat > "$CPANEL_LICENSE_DIR/config" << CONFIGEOF
# ATP Hosting 24 License Configuration
LICENSE_PROVIDER=atphosting24
LICENSE_UPDATE_URL=https://script.atphosting24.com
LICENSE_CHECK_INTERVAL=86400
AUTO_UPDATE=true
LAST_UPDATE=$(date '+%Y-%m-%d %H:%M:%S')
CONFIGEOF

    chmod 600 "$CPANEL_LICENSE_DIR/config"
    chown root:root "$CPANEL_LICENSE_DIR/config"
    log_info "Configuration updated"

    # Step 4: Ensure lsel binary is in place
    log_step "Verifying license check binary..."
    if [[ ! -f /usr/local/cpanel/cpanel_lsel/lsel ]]; then
        mkdir -p /usr/local/cpanel/cpanel_lsel/
        cat > /usr/local/cpanel/cpanel_lsel/lsel << 'LSELEOF'
#!/usr/bin/bash
# ATP Hosting 24 - License Check
echo "Active"
echo "License Type: Internal"
echo "Provider: ATP Hosting 24"
echo "Server: script.atphosting24.com"
exit 0
LSELEOF

        chmod 755 /usr/local/cpanel/cpanel_lsel/lsel
        chown root:root /usr/local/cpanel/cpanel_lsel/lsel
        log_info "License check binary recreated"
    fi

    # Step 5: Ensure lsof wrapper is in place
    if [[ ! -f /usr/local/cpanel/cpanel_lsel/lsof ]]; then
        cat > /usr/local/cpanel/cpanel_lsel/lsof << 'LSOFEOF'
#!/usr/bin/bash
# ATP Hosting 24 - lsof wrapper
/usr/sbin/lsof "$@"
LSOFEOF

        chmod 755 /usr/local/cpanel/cpanel_lsel/lsof
    fi

    # Step 6: Ensure license check wrappers are in place
    log_step "Verifying license check wrappers..."

    if [[ ! -f /usr/local/cpanel/bin/check_cpanel_lp ]] || ! grep -q "atphosting24" /usr/local/cpanel/bin/check_cpanel_lp 2>/dev/null; then
        cat > /usr/local/cpanel/bin/check_cpanel_lp << 'CHECKEOF'
#!/usr/bin/bash
# ATP Hosting 24 - License Check
echo "1"
echo "Active"
echo "License: ATP Hosting 24 Internal"
exit 0
CHECKEOF

        chmod 755 /usr/local/cpanel/bin/check_cpanel_lp
        log_info "License check wrapper updated"
    fi

    if [[ -d /usr/local/cpanel/whostmgr/bin/ ]]; then
        if [[ ! -f /usr/local/cpanel/whostmgr/bin/licensecheck ]] || ! grep -q "atphosting24" /usr/local/cpanel/whostmgr/bin/licensecheck 2>/dev/null; then
            cat > /usr/local/cpanel/whostmgr/bin/licensecheck << 'WHECKEOF'
#!/usr/bin/bash
# ATP Hosting 24 - WHM License Check
echo "1"
echo "Active"
echo "License: ATP Hosting 24 Internal"
exit 0
WHECKEOF

            chmod 755 /usr/local/cpanel/whostmgr/bin/licensecheck
            log_info "WHM license check wrapper updated"
        fi
    fi

    # Step 7: Patch cPanel binary for license verification
    log_step "Patching cPanel license verification..."
    if [[ -f /usr/local/cpanel/cpanel ]]; then
        if command -v perl &> /dev/null; then
            perl -pi -e 's/cpanel\.net/atphosting24\.com/g' /usr/local/cpanel/cpanel 2>/dev/null || true
            perl -pi -e 's/verify\.cpanel\.net/script\.atphosting24\.com/g' /usr/local/cpanel/cpanel 2>/dev/null || true
            log_info "cPanel binary patched"
        fi
    fi

    # Step 8: Ensure cron job is set up
    log_step "Verifying cron job..."
    if ! crontab -l 2>/dev/null | grep -q "update_cpanelv2"; then
        (crontab -l 2>/dev/null; echo "0 */12 * * * /usr/bin/update_cpanelv2 >> /var/log/atphosting24_license.log 2>&1") | crontab -
        log_info "Cron job configured"
    fi

    # Step 9: Restart cPanel to apply changes
    log_step "Restarting cPanel services..."
    /usr/local/cpanel/cpanel -restart 2>/dev/null || systemctl restart cpanel 2>/dev/null || true

    # Step 10: Verify license status
    log_step "Verifying license status..."
    sleep 2

    if [[ -f "$CPANEL_LICENSE_DIR/license" ]]; then
        log_info "License file: OK"
    else
        log_error "License file: MISSING"
    fi

    if [[ -f /usr/local/cpanel/cpanel_lsel/lsel ]]; then
        log_info "License check binary: OK"
    else
        log_error "License check binary: MISSING"
    fi

    echo "$TIMESTAMP - License update completed successfully" >> "$LOG_FILE"

    echo ""
    echo -e "${GREEN}═════════════════════════════════════════════════════════════${NC}"
    echo -e "${GREEN}  ATP Hosting 24 Licensing System Updated Successfully!${NC}"
    echo -e "${GREEN}  Next auto-update: in 12 hours${NC}"
    echo -e "${GREEN}═════════════════════════════════════════════════════════════${NC}"
}

# Show status
show_status() {
    print_banner
    echo -e "${CYAN}  ATP Hosting 24 cPanel Licensing System Status${NC}"
    echo -e "${CYAN}═════════════════════════════════════════════════════════════${NC}"

    echo ""
    echo -e "  ${BLUE}License Directory:${NC}"
    if [[ -d "$CPANEL_LICENSE_DIR" ]]; then
        echo -e "    ${GREEN}✓${NC} $CPANEL_LICENSE_DIR (exists)"

        if [[ -f "$CPANEL_LICENSE_DIR/license" ]]; then
            echo -e "    ${GREEN}✓${NC} License file present"
            echo ""
            cat "$CPANEL_LICENSE_DIR/license" | while read line; do
                echo -e "      $line"
            done
        else
            echo -e "    ${RED}✗${NC} License file missing"
        fi

        if [[ -f "$CPANEL_LICENSE_DIR/config" ]]; then
            echo -e "    ${GREEN}✓${NC} Config file present"
        else
            echo -e "    ${RED}✗${NC} Config file missing"
        fi
    else
        echo -e "    ${RED}✗${NC} License directory not found"
    fi

    echo ""
    echo -e "  ${BLUE}License Check Binary:${NC}"
    if [[ -f /usr/local/cpanel/cpanel_lsel/lsel ]]; then
        echo -e "    ${GREEN}✓${NC} lsel binary present"
    else
        echo -e "    ${RED}✗${NC} lsel binary missing"
    fi

    echo ""
    echo -e "  ${BLUE}Update Script:${NC}"
    if [[ -f /usr/bin/update_cpanelv2 ]]; then
        echo -e "    ${GREEN}✓${NC} /usr/bin/update_cpanelv2 (installed)"
    else
        echo -e "    ${RED}✗${NC} Update script not found"
    fi

    echo ""
    echo -e "  ${BLUE}Cron Job:${NC}"
    CRON_ENTRY=$(crontab -l 2>/dev/null | grep "update_cpanelv2")
    if [[ -n "$CRON_ENTRY" ]]; then
        echo -e "    ${GREEN}✓${NC} $CRON_ENTRY"
    else
        echo -e "    ${RED}✗${NC} No cron job found"
    fi

    echo ""
    echo -e "  ${BLUE}SSL Certificate:${NC}"
    if [[ -f /var/cpanel/ssl/cpanel/cpanel.pem ]]; then
        echo -e "    ${GREEN}✓${NC} SSL certificate present"
        openssl x509 -in /var/cpanel/ssl/cpanel/cpanel.pem -noout -subject -dates 2>/dev/null | while read line; do
            echo -e "      $line"
        done
    else
        echo -e "    ${RED}✗${NC} SSL certificate not found"
    fi

    echo ""
    echo -e "  ${BLUE}cPanel Services:${NC}"
    if systemctl is-active cpanel &>/dev/null; then
        echo -e "    ${GREEN}✓${NC} cPanel service: active"
    else
        echo -e "    ${YELLOW}!${NC} cPanel service: not active (may use different service name)"
    fi

    echo ""
    echo -e "${CYAN}═════════════════════════════════════════════════════════════${NC}"
}

# Show help
show_help() {
    print_banner
    echo -e "${CYAN}  ATP Hosting 24 - cPanel License Manager${NC}"
    echo ""
    echo -e "  ${YELLOW}Usage:${NC} update_cpanelv2 [OPTION]"
    echo ""
    echo -e "  ${YELLOW}Options:${NC}"
    echo -e "    (no option)        Update the licensing system"
    echo -e "    --Uninstall        Uninstall the licensing system"
    echo -e "    --ssl-services     Install SSL for hostname"
    echo -e "    --status           Show licensing system status"
    echo -e "    --help, -h         Show this help message"
    echo ""
    echo -e "  ${YELLOW}Examples:${NC}"
    echo -e "    ${GREEN}update_cpanelv2${NC}                 # Update license"
    echo -e "    ${GREEN}update_cpanelv2 --Uninstall${NC}     # Uninstall"
    echo -e "    ${GREEN}update_cpanelv2 --ssl-services${NC}  # Install SSL"
    echo -e "    ${GREEN}update_cpanelv2 --status${NC}        # Show status"
    echo ""
    echo -e "  ${YELLOW}Full Install Command:${NC}"
    echo -e "    ${GREEN}bash <( curl -4 https://script.atphosting24.com/pre.sh ) cPanel && /usr/bin/update_cpanelv2${NC}"
    echo ""
}

#====================================================
# Main - Handle command line arguments
#====================================================
case "$1" in
    --Uninstall)
        check_root
        uninstall_license
        ;;
    --ssl-services)
        check_root
        install_ssl
        ;;
    --status)
        show_status
        ;;
    --help|-h)
        show_help
        ;;
    "")
        check_root
        update_license
        ;;
    *)
        echo -e "${RED}Unknown option: $1${NC}"
        show_help
        exit 1
        ;;
esac
