#!/usr/bin/env bash

#################################
#      ISPProtect BanDaemon     #
#   (c) 2025 by ISPConfig UG    #
#      all rights reserved      #
#################################

# Script initialization
set -euo pipefail  # Enable strict error handling

# Get script directory (resolve symlinks to find actual installation)
if [[ -L "${BASH_SOURCE[0]}" ]]; then
    # Script is a symlink, resolve to actual location
    SCRIPT_DIR="$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")" && pwd)"
else
    # Script is not a symlink
    SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
fi
CURRENT_DIR="$PWD"

# Configuration
MODE="${1:-}"
CONFIG_FILE="${SCRIPT_DIR}/ispp_php.ini"

# Function to log messages
log_message() {
    if [[ "${NO_OUT:-}" != "1" ]]; then
        echo "$1" >&2
    fi
}

# Function to detect PHP binary
detect_php() {
    if [[ -n "${PHP:-}" ]]; then
        return 0
    fi
    
    # Try common PHP locations (newest first)
    for php_binary in php php8.3 php8.2 php8.1 php8.0 php7.4 php7.3 php7.2 php7.1 php7.0 php5.6; do
        if command -v "$php_binary" >/dev/null 2>&1; then
            PHP="$php_binary"
            return 0
        fi
    done
    
    log_message "Error: No PHP binary found in PATH"
    exit 1
}

# Function to get PHP version
get_php_version() {
    local version
    version=$($PHP -r "echo PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION;" 2>/dev/null || echo "")
    
    if [[ -z "$version" ]]; then
        log_message "Error: Could not determine PHP version"
        exit 1
    fi
    
    echo "$version"
}

# Function to validate PHP version
validate_php_version() {
    local version="$1"
    local major_version="${version%%.*}"
    
    # Check for minimum PHP version (5.6+)
    if [[ "$major_version" -lt "5" ]] || [[ "$version" == "5.0" ]] || [[ "$version" == "5.1" ]] || [[ "$version" == "5.2" ]] || [[ "$version" == "5.3" ]] || [[ "$version" == "5.4" ]] || [[ "$version" == "5.5" ]]; then
        log_message "Error: PHP version $version is not supported. Minimum required: PHP 5.6"
        exit 1
    fi
    
    if [[ "$major_version" -gt "8" ]] || [[ "$version" > "8.3" ]]; then
        log_message "Warning: PHP version $version may not be fully tested"
    fi
}

# Function to create PHP configuration
create_php_config() {
    local config_file="$1"
    
    # Remove existing config
    rm -f "$config_file"
    
    # Create basic PHP configuration
    cat > "$config_file" << 'EOF'
; ISPProtect BanDaemon PHP Configuration
disable_functions=
max_execution_time=0
memory_limit=512M
display_errors=Off
log_errors=On
error_reporting=E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE & ~E_WARNING
EOF
    
    # Append local configuration if it exists
    local local_config="${SCRIPT_DIR}/ispp_php.ini.local"
    if [[ -f "$local_config" ]]; then
        echo "" >> "$config_file"
        echo "; Local configuration overrides" >> "$config_file"
        cat "$local_config" >> "$config_file"
    fi
}

# Function to setup SourceGuardian loader
setup_sourceguardian_loader() {
    local config_file="$1"
    
    # Check if loader script exists
    local loader_script="${SCRIPT_DIR}/ispp_loader.php"
    if [[ ! -f "$loader_script" ]]; then
        log_message "Warning: SourceGuardian loader script not found: $loader_script"
        return 0
    fi
    
    # log_message "Checking SourceGuardian loader..."
    
    # Run the loader script to get the extension path
    local sgcheck
    sgcheck=$($PHP -n -c "$config_file" -q "$loader_script" 2>/dev/null || echo "ERR")
    
    if [[ "$sgcheck" == "ERR" ]]; then
        log_message "Error: Failed downloading SourceGuardian Loader. Please install manually."
        exit 1
    elif [[ -n "$sgcheck" ]]; then
        # Add the extension to PHP configuration
        echo "" >> "$config_file"
        echo "; SourceGuardian loader extension" >> "$config_file"
        echo "extension=$sgcheck" >> "$config_file"
        # log_message "SourceGuardian loader configured: $sgcheck"
    fi
}

# Function to check if script exists
check_script() {
    local script_path="$1"
    
    if [[ ! -f "$script_path" ]]; then
        log_message "Error: Script not found: $script_path"
        exit 1
    fi
    
    if [[ ! -r "$script_path" ]]; then
        log_message "Error: Script not readable: $script_path"
        exit 1
    fi
}

# Function to run PHP script
run_php_script() {
    local script="$1"
    shift
    local args=("$@")
    
    local script_path="${SCRIPT_DIR}/${script}"
    check_script "$script_path"
    
    if [[ "$script" == "ispp_bandaemon.php" ]]; then
        # Run daemon in background
        exec $PHP -c "$CONFIG_FILE" -q "$script_path" "${args[@]}" &
        disown
    else
        # Run script directly
        exec $PHP -c "$CONFIG_FILE" -q "$script_path" "${args[@]}"
    fi
}

# Function to perform update
perform_update() {
    log_message "ISPProtect BanDaemon Update Process"
    log_message "==================================="
    
    # Check if running as root
    if [[ $EUID -ne 0 ]]; then
        log_message "Error: Update must be run as root"
        exit 1
    fi
    
    # Check for required commands
    for cmd in wget tar; do
        if ! command -v "$cmd" >/dev/null 2>&1; then
            log_message "Error: Required command '$cmd' not found"
            exit 1
        fi
    done
    
    # Create temporary directory
    TEMP_DIR=$(mktemp -d -t ispprotect_update.XXXXXX)
    if [[ ! -d "$TEMP_DIR" ]]; then
        log_message "Error: Could not create temporary directory"
        exit 1
    fi
    
    # Cleanup function
    cleanup() {
        if [[ -d "$TEMP_DIR" ]]; then
            rm -rf "$TEMP_DIR"
        fi
    }
    trap cleanup EXIT
    
    log_message "Downloading latest version..."
    
    # Download the latest package
    DOWNLOAD_URL="https://www.ispprotect.com/download/ispp_bandaemon.tar.gz"
    if ! wget -q --timeout=30 --tries=3 -O "$TEMP_DIR/ispp_bandaemon.tar.gz" "$DOWNLOAD_URL"; then
        log_message "Error: Failed to download update package from $DOWNLOAD_URL"
        log_message "Please check your internet connection and try again"
        exit 1
    fi
    
    log_message "Download completed successfully"
    log_message "Extracting package..."
    
    # Extract the package
    cd "$TEMP_DIR"
    if ! tar -xzf ispp_bandaemon.tar.gz; then
        log_message "Error: Failed to extract update package"
        exit 1
    fi
    
    # Check if extraction was successful
    if [[ ! -d "bandaemon_install" ]]; then
        log_message "Error: Invalid package structure - 'bandaemon_install' directory not found"
        exit 1
    fi
    
    # Check if install.sh exists
    if [[ ! -f "bandaemon_install/install.sh" ]]; then
        log_message "Error: install.sh not found in update package"
        exit 1
    fi
    
    log_message "Package extracted successfully"
    log_message "Starting update installation..."
    log_message ""
    
    # Change to the installation directory and run install.sh
    cd bandaemon_install
    chmod +x install.sh
    
    # Run the installer
    if ! bash install.sh; then
        log_message ""
        log_message "Error: Update installation failed"
        exit 1
    fi
    
    log_message ""
    log_message "Update completed successfully!"
    log_message "The ISPProtect BanDaemon has been updated to the latest version."
}

# Function to show help
show_help() {
    cat << 'EOF'

============================================
Available arguments for ISPProtect BanDaemon
============================================

Reporting:
  --report [--email=recipient@domain.com,other@domain2.com] [--screen] [--today]
      Send report email
      --screen: Show report on screen instead of sending email
      --today:  Show report for today instead of yesterday

IP Management:
  --ban=<ip> --bantime=<num>[SMHD]
      Ban <ip> for <num> [S]econds, [M]inutes, [H]ours or [D]ays
  --unban=<ip>
      Unban <ip>
  --whitelist=<ip> [--remove]
      Add <ip> to whitelist or remove it if --remove is set
  --showbans [--ip=<ip>]
      Show current bans, optionally filtered by IP

Utilities:
  --unbanbots
      Unban known search engine bots
  --rbl
      Generate DNS blacklist files
  --abuse evidence/<filename>
      Send abuse email to abuse contact from whois

System Management:
  --update
      Download and install the latest version from ISPProtect.com
      (requires root privileges)

Daemon:
  (no arguments)
      Start the BanDaemon in background

General:
  --help
      Show this help message
  --version
      Show version information

Examples:
  ispp_bandaemon                                    # Start daemon
  ispp_bandaemon --ban=192.168.1.100 --bantime=1H  # Ban IP for 1 hour
  ispp_bandaemon --report --screen                  # Show report on screen
  ispp_bandaemon --whitelist=192.168.1.1            # Add IP to whitelist
  ispp_bandaemon --update                           # Update to latest version

EOF
}

# Main execution starts here
main() {
    # Detect PHP binary
    detect_php
    
    # Get and validate PHP version
    PHP_VERSION=$(get_php_version)
    validate_php_version "$PHP_VERSION"
    
    # Create PHP configuration
    create_php_config "$CONFIG_FILE"
    
    # Setup SourceGuardian loader
    setup_sourceguardian_loader "$CONFIG_FILE"
    
    # Process command line arguments
    case "${MODE:-}" in
        "--report")
            run_php_script "ispp_bd_report.php" "$@"
            ;;
        "--abuse")
            if [[ $# -lt 2 ]]; then
                log_message "Error: --abuse requires evidence file argument"
                exit 1
            fi
            run_php_script "ispp_bd_abusemail.php" "$2"
            ;;
        "--ban="*|"--unban="*|"--unbanbots"|"--rbl"|"--showbans"|"--whitelist="*|"--version")
            run_php_script "ispp_bd_helper.php" "$@"
            ;;
        "--update")
            perform_update
            ;;
        "--help")
            show_help
            ;;
        "")
            # Start daemon
            log_message "Starting ISPProtect BanDaemon (PHP $PHP_VERSION)..."
            run_php_script "ispp_bandaemon.php"
            ;;
        *)
            log_message "Error: Unknown argument: $MODE"
            log_message "Use --help for available options"
            exit 1
            ;;
    esac
}

# Execute main function
main "$@"
