#!/bin/bash
# ============================================================================
# RCP License Pre-Installation Script (pre.sh)
# ============================================================================
# Downloads and installs the RCP license manager binary from api.licensercp.com
# License authorization is IP-based — no token needed.
#
# Usage:
#   bash pre.sh
#
# After install, use RCP to install software licenses:
#   rcp -install cpanel
#   rcp -install cloudlinux
#   rcp -install litespeed
#   rcp --list
# ============================================================================

set -euo pipefail

# ============================================================================
# Configuration
# ============================================================================
readonly RCP_BINARY_NAME="rcp"
readonly RCP_BINARY_PATH="/usr/bin/${RCP_BINARY_NAME}"
readonly RCP_DOWNLOAD_URL="https://api.licensercp.com/rcp.bin"
readonly RCP_DATA_DIR="/usr/local/syslic/data"
readonly LOG_FILE="/var/log/rcp_install.log"

# ============================================================================
# Supported Software List
# ============================================================================
readonly -a SOFTWARE_LIST=(
    "cpanel        - cPanel/WHM License (VPS)"
    "dcpanel       - cPanel/WHM License (Dedicated)"
    "cloudlinux    - CloudLinux OS License"
    "litespeed     - LiteSpeed Web Server License"
    "litespeedX    - LiteSpeed Web Server License (Extended)"
    "imunify360    - Imunify360 Security License"
    "softaculous   - Softaculous Auto Installer License"
    "webuzo        - Webuzo Control Panel License"
    "cxs           - ConfigServer eXploit Scanner License"
    "sitepad       - SitePad Website Builder License"
    "whmreseller   - WHM Reseller License"
    "jetbackup     - JetBackup License"
    "plesk         - Plesk Control Panel License (VPS)"
    "dplesk        - Plesk Control Panel License (Dedicated)"
    "virtualizor   - Virtualizor VPS Panel License"
)

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

# ============================================================================
# Logging
# ============================================================================
log() {
    local timestamp
    timestamp=$(date +"%Y-%m-%d %H:%M:%S")
    echo "[$timestamp] $*" >> "$LOG_FILE" 2>/dev/null || true
}

# ============================================================================
# Root Check
# ============================================================================
if [[ $EUID -ne 0 ]]; then
    echo -e "${RED}You must be a root user${NC}" >&2
    exit 1
fi

# ============================================================================
# Architecture Check
# ============================================================================
arch=$(uname -m)

case "$arch" in
    i*86)
        echo -e "${RED}We no longer support 32-bit versions. Please contact support!${NC}"
        exit 1
        ;;
    aarch64)
        echo -e "${RED}We no longer support aarch64 versions. Please contact support!${NC}"
        exit 1
        ;;
    x86_64)
        # Supported
        ;;
    *)
        echo -e "${YELLOW}Warning: Unsupported architecture: ${arch}. Installation may fail.${NC}"
        log "WARN: Unsupported architecture: ${arch}"
        ;;
esac

# ============================================================================
# OS Detection (Single Pass)
# ============================================================================
DETECTED_OS=""
DETECTED_VERSION=""
DETECTED_PRETTY=""
PKG_MANAGER=""

if [[ -f /etc/os-release ]]; then
    # shellcheck disable=SC1091
    source /etc/os-release
    DETECTED_OS="${NAME:-}"
    DETECTED_VERSION="${VERSION_ID:-}"
    DETECTED_PRETTY="${PRETTY_NAME:-}"
elif type lsb_release &>/dev/null; then
    DETECTED_OS=$(lsb_release -si)
    DETECTED_VERSION=$(lsb_release -sr)
    DETECTED_PRETTY="${DETECTED_OS} ${DETECTED_VERSION}"
else
    echo -e "${RED}Unsupported OS. Cannot detect operating system.${NC}"
    exit 1
fi

OS_MAJOR="${DETECTED_VERSION%%.*}"

# Determine package manager
if [[ -f /etc/redhat-release ]]; then
    # Check for CentOS Stream
    if grep -q 'CentOS Stream' /etc/redhat-release 2>/dev/null; then
        echo -e "${RED}CentOS Stream detected.${NC}"
        echo -e "${RED}You cannot use CentOS Stream for our licensing system.${NC}"
        echo -e "${RED}Please install a supported operating system.${NC}"
        exit 1
    fi
    # CentOS 8+ / RHEL 8+ / AlmaLinux 8+ use dnf
    if [[ "${OS_MAJOR}" -ge 8 ]] 2>/dev/null; then
        PKG_MANAGER="dnf"
    else
        PKG_MANAGER="yum"
    fi
elif [[ "${DETECTED_OS}" == "Ubuntu" ]] || [[ "${DETECTED_OS}" == "Debian"* ]]; then
    PKG_MANAGER="apt-get"
else
    # Fallback
    if command -v dnf &>/dev/null; then
        PKG_MANAGER="dnf"
    elif command -v yum &>/dev/null; then
        PKG_MANAGER="yum"
    elif command -v apt-get &>/dev/null; then
        PKG_MANAGER="apt-get"
    else
        echo -e "${RED}Cannot determine package manager for ${DETECTED_OS}.${NC}"
        exit 1
    fi
fi

log "INFO: OS=${DETECTED_OS} ${DETECTED_VERSION}, PKG_MANAGER=${PKG_MANAGER}"

# ============================================================================
# Display System Information
# ============================================================================
CPU=$(lscpu 2>/dev/null | grep "Model name" | cut -d: -f2 | sed 's/^[ \t]*//')
RAM=$(free -h 2>/dev/null | awk '/^Mem:/ {print $2}')
DISK=$(df -h / 2>/dev/null | awk '/^\/dev/ {print $2}')
LOAD=$(uptime 2>/dev/null | awk -F'load average:' '{print $2}' | sed 's/,//g' | xargs)
TIME=$(date +"%Y-%m-%d %H:%M:%S")

echo ""
echo -e "${BLUE}${BOLD}=====================================================================${NC}"
echo -e "${BLUE}${BOLD}                    RCP License Manager Installer                    ${NC}"
echo -e "${BLUE}${BOLD}=====================================================================${NC}"
echo ""
echo -e "${BOLD}System Information:${NC}"
echo -e "${BOLD}OS:${NC}           ${DETECTED_PRETTY:-Unknown}"
echo -e "${BOLD}CPU:${NC}          ${CPU:-Unknown}"
echo -e "${BOLD}RAM:${NC}          ${RAM:-Unknown}"
echo -e "${BOLD}Disk:${NC}         ${DISK:-Unknown}"
echo -e "${BOLD}Load:${NC}         ${LOAD:-Unknown}"
echo -e "${BOLD}Current Time:${NC} ${TIME}"
echo ""

# ============================================================================
# Ensure DNS (RedHat only, auto-fix missing nameserver)
# ============================================================================
ensure_dns() {
    if [[ ! -f /etc/redhat-release ]]; then
        return 0
    fi
    if ! grep -m1 -q '^nameserver' /etc/resolv.conf 2>/dev/null; then
        echo -e "${YELLOW}No nameserver found. Adding Google DNS to /etc/resolv.conf...${NC}"
        {
            echo ""
            echo "nameserver 8.8.8.8"
            echo "nameserver 8.8.4.4"
        } >> /etc/resolv.conf
        log "INFO: Added Google DNS to /etc/resolv.conf"
    fi
}

ensure_dns

# ============================================================================
# Disable MySQL Community Repo (if present, avoids conflicts)
# ============================================================================
if [[ -f /etc/yum.repos.d/mysql-community.repo ]]; then
    echo -e "${YELLOW}Disabling MySQL community repo to avoid conflicts...${NC}"
    sed -i 's|enabled=1|enabled=0|g' /etc/yum.repos.d/mysql-community.repo
    log "INFO: Disabled MySQL community repo"
fi

# ============================================================================
# Install Required Tools
# ============================================================================
declare -a missing_tools=()
declare -a packages_to_install=()

# Check each required tool
for tool in wget curl sudo openssl tar unzip; do
    if ! command -v "$tool" &>/dev/null; then
        missing_tools+=("$tool")
        echo -e "${YELLOW}Required tool '${tool}' is not installed.${NC}"
    fi
done

# Map missing tools to package names
for cmd in "${missing_tools[@]}"; do
    case "$cmd" in
        wget)    packages_to_install+=("wget") ;;
        curl)    packages_to_install+=("curl") ;;
        sudo)    packages_to_install+=("sudo") ;;
        openssl) packages_to_install+=("openssl") ;;
        tar)     packages_to_install+=("tar") ;;
        unzip)   packages_to_install+=("unzip") ;;
    esac
done

# Add OS-specific SSL libraries
if [[ -f /etc/redhat-release ]]; then
    if [[ "${OS_MAJOR}" -le 7 ]] 2>/dev/null; then
        packages_to_install+=("openssl-devel" "compat-openssl10")
    else
        packages_to_install+=("openssl-libs")
    fi
elif [[ "${DETECTED_OS}" == "Ubuntu" ]] || [[ "${DETECTED_OS}" == "Debian"* ]]; then
    packages_to_install+=("libssl-dev")
fi

# Remove duplicates
IFS=" " read -r -a packages_to_install <<< "$(echo "${packages_to_install[@]}" | tr ' ' '\n' | sort -u | tr '\n' ' ')"

# Install missing packages
if [[ ${#packages_to_install[@]} -gt 0 ]]; then
    echo -e "${BLUE}Installing required packages: ${packages_to_install[*]}...${NC}"
    case "${PKG_MANAGER}" in
        apt-get)
            apt-get update -qq 2>/dev/null || true
            apt-get install -y "${packages_to_install[@]}" 2>&1 | tee -a "$LOG_FILE"
            ;;
        yum)
            yum install -y "${packages_to_install[@]}" 2>&1 | tee -a "$LOG_FILE"
            ;;
        dnf)
            dnf install -y "${packages_to_install[@]}" 2>&1 | tee -a "$LOG_FILE"
            ;;
    esac
    log "INFO: Installed packages: ${packages_to_install[*]}"
fi

# ============================================================================
# Download RCP Binary (with SSL fallback and verification)
# ============================================================================
echo -n "Downloading RCP license manager... "

# Try with SSL verification first, then fallback to --no-check-certificate
download_success=0

# Attempt 1: wget with SSL verification
wget -q --timeout=15 --tries=3 -O "${RCP_BINARY_PATH}" "${RCP_DOWNLOAD_URL}" 2>/dev/null
wget_exit=$?

if [[ $wget_exit -ne 0 ]]; then
    # Attempt 2: wget without SSL verification (self-signed cert)
    echo -n "retrying (SSL)... "
    wget -q --no-check-certificate --timeout=15 --tries=3 -O "${RCP_BINARY_PATH}" "${RCP_DOWNLOAD_URL}" 2>/dev/null
    wget_exit=$?
fi

if [[ $wget_exit -ne 0 ]]; then
    # Attempt 3: curl fallback
    echo -n "retrying (curl)... "
    curl -fsSL -o "${RCP_BINARY_PATH}" "${RCP_DOWNLOAD_URL}" 2>/dev/null
    curl_exit=$?

    if [[ $curl_exit -ne 0 ]]; then
        # Attempt 4: curl without SSL verification
        echo -n "retrying (curl -k)... "
        curl -fsSLk -o "${RCP_BINARY_PATH}" "${RCP_DOWNLOAD_URL}" 2>/dev/null
        curl_exit=$?
        wget_exit=$curl_exit
    else
        wget_exit=0
    fi
fi

if [[ $wget_exit -eq 0 ]] && [[ -f "${RCP_BINARY_PATH}" ]]; then
    # Verify the downloaded file is a valid ELF binary
    file_size=$(stat -c%s "${RCP_BINARY_PATH}" 2>/dev/null || echo "0")

    if [[ "${file_size}" -lt 1000 ]]; then
        echo ""
        echo -e "${RED}Downloaded file is too small (${file_size} bytes) — likely an error page.${NC}"
        # Show the file content for debugging
        head -c 500 "${RCP_BINARY_PATH}" 2>/dev/null | head -5
        echo ""
        rm -f "${RCP_BINARY_PATH}"
        log "ERROR: Downloaded file too small (${file_size} bytes)"
        exit 1
    fi

    # Check if it's a valid ELF binary
    file_type=$(file "${RCP_BINARY_PATH}" 2>/dev/null)
    if ! echo "${file_type}" | grep -q "ELF.*executable"; then
        echo ""
        echo -e "${RED}Downloaded file is not a valid binary.${NC}"
        echo -e "${YELLOW}File type: ${file_type}${NC}"
        # Show first few lines of the file for debugging
        head -c 500 "${RCP_BINARY_PATH}" 2>/dev/null | head -5
        echo ""
        rm -f "${RCP_BINARY_PATH}"
        log "ERROR: Downloaded file is not a valid ELF binary: ${file_type}"
        exit 1
    fi

    echo -e "${GREEN}Completed! (${file_size} bytes)${NC}"
    log "INFO: Downloaded ${RCP_BINARY_NAME} from ${RCP_DOWNLOAD_URL} (${file_size} bytes)"

    chmod +x "${RCP_BINARY_PATH}"
    chmod_exit=$?
    if [[ $chmod_exit -ne 0 ]]; then
        echo ""
        echo -e "${RED}Exit code: ${chmod_exit} - Failed to make ${RCP_BINARY_PATH} executable. Contact support.${NC}"
        log "ERROR: chmod +x failed for ${RCP_BINARY_PATH} (exit: ${chmod_exit})"
        exit 1
    fi
else
    echo ""
    echo -e "${RED}File download failed (exit code: ${wget_exit}).${NC}"
    echo -e "${RED}Please check your network connection and try again.${NC}"
    echo -e "${YELLOW}URL: ${RCP_DOWNLOAD_URL}${NC}"
    log "ERROR: Download failed from ${RCP_DOWNLOAD_URL} (exit: ${wget_exit})"
    exit 1
fi

# ============================================================================
# Create Data Directory
# ============================================================================
mkdir -p /usr/local/syslic/ "${RCP_DATA_DIR}"
log "INFO: Created data directory: ${RCP_DATA_DIR}"

# ============================================================================
# Summary
# ============================================================================
echo ""
echo -e "${GREEN}${BOLD}=====================================================================${NC}"
echo -e "${GREEN}${BOLD}                  RCP License Manager Installed!                     ${NC}"
echo -e "${GREEN}${BOLD}=====================================================================${NC}"
echo ""
echo -e "${BOLD}Binary:${NC}    ${RCP_BINARY_PATH}"
echo -e "${BOLD}Data:${NC}      ${RCP_DATA_DIR}"
echo -e "${BOLD}Log:${NC}       ${LOG_FILE}"
echo ""
echo -e "${YELLOW}Your license is authorized by server IP address.${NC}"
echo -e "${YELLOW}No token required — just run the command for your software:${NC}"
echo ""
echo -e "${CYAN}${BOLD}Supported Software:${NC}"
echo ""
for sw in "${SOFTWARE_LIST[@]}"; do
    echo -e "  ${GREEN}${BOLD}rcp -install${NC} ${sw}"
done
echo ""
echo -e "${CYAN}Example:${NC}"
echo -e "  ${BOLD}rcp -install cpanel${NC}          (Install cPanel/WHM license)"
echo -e "  ${BOLD}rcp -install cloudlinux${NC}      (Install CloudLinux license)"
echo -e "  ${BOLD}rcp -install litespeed${NC}       (Install LiteSpeed license)"
echo -e "  ${BOLD}rcp -install imunify360${NC}      (Install Imunify360 license)"
echo ""

log "INFO: Installation completed successfully"
exit 0
