#!/bin/bash

#############################################################################
# Service Information Mapping
# Derives service names, users, and configuration based on platform
# Must be sourced AFTER lib/system-detect.sh has set SYS_* variables
#############################################################################

# Source guard
if [ -n "${_SERVICE_INFO_LOADED:-}" ]; then
    return 0
fi
readonly _SERVICE_INFO_LOADED=1

#############################################################################
# WEB SERVER SERVICE INFORMATION
#############################################################################

derive_web_service_info() {
    case "$SYS_WEB_SERVER" in
        apache|httpd)
            # Apache/httpd service and user info
            if [ "$SYS_OS_TYPE" = "ubuntu" ] || [ "$SYS_OS_TYPE" = "debian" ]; then
                export SYS_WEB_SERVICE="apache2"
                export SYS_WEB_USER="www-data"
                export SYS_WEB_GROUP="www-data"
                export SYS_WEB_CONFIG_DIR="/etc/apache2"
                export SYS_WEB_MODULES_DIR="/etc/apache2/mods-enabled"
                export SYS_WEB_VHOSTS_DIR="/etc/apache2/sites-enabled"
            else
                # RHEL/CentOS/AlmaLinux
                export SYS_WEB_SERVICE="httpd"
                export SYS_WEB_USER="apache"
                export SYS_WEB_GROUP="apache"
                export SYS_WEB_CONFIG_DIR="/etc/httpd/conf"
                export SYS_WEB_MODULES_DIR="/etc/httpd/modules"
                export SYS_WEB_VHOSTS_DIR="/etc/httpd/conf.d"
            fi
            export SYS_WEB_PID_FILE="/var/run/apache2.pid"
            ;;
        nginx)
            # Nginx service and user info (mostly consistent)
            export SYS_WEB_SERVICE="nginx"
            export SYS_WEB_USER="nginx"
            export SYS_WEB_GROUP="nginx"
            export SYS_WEB_CONFIG_DIR="/etc/nginx"
            export SYS_WEB_VHOSTS_DIR="/etc/nginx/conf.d"
            export SYS_WEB_PID_FILE="/var/run/nginx.pid"
            ;;
        litespeed|openlitespeed)
            # LiteSpeed service info
            export SYS_WEB_SERVICE="lsws"
            export SYS_WEB_USER="nobody"
            export SYS_WEB_GROUP="nobody"
            export SYS_WEB_CONFIG_DIR="/usr/local/lsws/conf"
            export SYS_WEB_VHOSTS_DIR="/usr/local/lsws/conf/vhconf.conf.d"
            export SYS_WEB_PID_FILE="/tmp/lsws.pid"
            ;;
        *)
            export SYS_WEB_SERVICE=""
            export SYS_WEB_USER=""
            export SYS_WEB_GROUP=""
            export SYS_WEB_CONFIG_DIR=""
            ;;
    esac
}

#############################################################################
# DATABASE SERVICE INFORMATION
#############################################################################

derive_db_service_info() {
    case "$SYS_DB_TYPE" in
        mysql)
            if [ "$SYS_OS_TYPE" = "ubuntu" ] || [ "$SYS_OS_TYPE" = "debian" ]; then
                export SYS_DB_SERVICE="mysql"
            else
                export SYS_DB_SERVICE="mysqld"
            fi
            export SYS_DB_USER="mysql"
            export SYS_DB_GROUP="mysql"
            ;;
        mariadb)
            if [ "$SYS_OS_TYPE" = "ubuntu" ] || [ "$SYS_OS_TYPE" = "debian" ]; then
                export SYS_DB_SERVICE="mariadb"
            else
                export SYS_DB_SERVICE="mariadb"
            fi
            export SYS_DB_USER="mysql"
            export SYS_DB_GROUP="mysql"
            ;;
        postgresql)
            export SYS_DB_SERVICE="postgresql"
            export SYS_DB_USER="postgres"
            export SYS_DB_GROUP="postgres"
            ;;
        *)
            export SYS_DB_SERVICE=""
            export SYS_DB_USER=""
            export SYS_DB_GROUP=""
            ;;
    esac
}

#############################################################################
# MAIL SERVICE INFORMATION
#############################################################################

derive_mail_service_info() {
    case "$SYS_MAIL_SYSTEM" in
        exim)
            export SYS_MAIL_SERVICE="exim"
            export SYS_MAIL_USER="mail"
            export SYS_MAIL_GROUP="mail"
            export SYS_MAIL_CONFIG="/etc/exim.conf"
            export SYS_MAIL_ALIAS_FILE="/etc/aliases"
            ;;
        postfix)
            export SYS_MAIL_SERVICE="postfix"
            export SYS_MAIL_USER="postfix"
            export SYS_MAIL_GROUP="postfix"
            export SYS_MAIL_CONFIG="/etc/postfix/main.cf"
            export SYS_MAIL_ALIAS_FILE="/etc/aliases"
            ;;
        sendmail)
            export SYS_MAIL_SERVICE="sendmail"
            export SYS_MAIL_USER="smmsp"
            export SYS_MAIL_GROUP="smmsp"
            export SYS_MAIL_CONFIG="/etc/mail/sendmail.cf"
            export SYS_MAIL_ALIAS_FILE="/etc/mail/aliases"
            ;;
        *)
            export SYS_MAIL_SERVICE=""
            export SYS_MAIL_USER=""
            export SYS_MAIL_GROUP=""
            ;;
    esac
}

#############################################################################
# SSH/AUTH SERVICE INFORMATION
#############################################################################

derive_auth_service_info() {
    export SYS_AUTH_SERVICE="sshd"

    case "$SYS_OS_TYPE" in
        ubuntu|debian)
            export SYS_AUTH_USER="root"
            export SYS_AUTH_CONFIG="/etc/ssh/sshd_config"
            ;;
        *)
            # RHEL/CentOS
            export SYS_AUTH_USER="root"
            export SYS_AUTH_CONFIG="/etc/ssh/sshd_config"
            ;;
    esac
}

#############################################################################
# FIREWALL SERVICE INFORMATION
#############################################################################

derive_firewall_service_info() {
    case "$SYS_FIREWALL" in
        csf)
            export SYS_FIREWALL_SERVICE="csf"
            export SYS_FIREWALL_CONFIG="/etc/csf/csf.conf"
            export SYS_FIREWALL_ALLOW="/etc/csf/csf.allow"
            export SYS_FIREWALL_DENY="/etc/csf/csf.deny"
            ;;
        firewalld)
            export SYS_FIREWALL_SERVICE="firewalld"
            export SYS_FIREWALL_CONFIG="/etc/firewalld"
            ;;
        iptables)
            export SYS_FIREWALL_SERVICE="iptables"
            export SYS_FIREWALL_CONFIG="/etc/sysconfig/iptables"
            ;;
        ufw)
            export SYS_FIREWALL_SERVICE="ufw"
            export SYS_FIREWALL_CONFIG="/etc/ufw"
            ;;
        *)
            export SYS_FIREWALL_SERVICE=""
            export SYS_FIREWALL_CONFIG=""
            ;;
    esac
}

#############################################################################
# PACKAGE MANAGER INFORMATION
#############################################################################

derive_package_manager_info() {
    case "$SYS_OS_TYPE" in
        ubuntu|debian)
            export SYS_PKG_MANAGER="apt"
            export SYS_PKG_MANAGER_CMD="apt-get"
            export SYS_PKG_MANAGER_UPDATE="apt-get update"
            export SYS_PKG_MANAGER_INSTALL="apt-get install -y"
            export SYS_PKG_MANAGER_REMOVE="apt-get remove -y"
            export SYS_PKG_MANAGER_UPGRADE="apt-get upgrade -y"
            ;;
        *)
            # RHEL/CentOS/AlmaLinux
            if command -v dnf &>/dev/null; then
                export SYS_PKG_MANAGER="dnf"
                export SYS_PKG_MANAGER_CMD="dnf"
                export SYS_PKG_MANAGER_UPDATE="dnf makecache"
                export SYS_PKG_MANAGER_INSTALL="dnf install -y"
                export SYS_PKG_MANAGER_REMOVE="dnf remove -y"
                export SYS_PKG_MANAGER_UPGRADE="dnf upgrade -y"
            else
                export SYS_PKG_MANAGER="yum"
                export SYS_PKG_MANAGER_CMD="yum"
                export SYS_PKG_MANAGER_UPDATE="yum makecache"
                export SYS_PKG_MANAGER_INSTALL="yum install -y"
                export SYS_PKG_MANAGER_REMOVE="yum remove -y"
                export SYS_PKG_MANAGER_UPGRADE="yum upgrade -y"
            fi
            ;;
    esac
}

#############################################################################
# INIT SYSTEM INFORMATION
#############################################################################

derive_init_system_info() {
    # Most modern systems use systemd, but support sysvinit fallback
    if [ -d "/run/systemd/system" ] || [ -d "/sys/fs/cgroup/systemd" ]; then
        export SYS_INIT_SYSTEM="systemd"
        export SYS_SERVICE_CMD="systemctl"
        export SYS_SERVICE_START="systemctl start"
        export SYS_SERVICE_STOP="systemctl stop"
        export SYS_SERVICE_RESTART="systemctl restart"
        export SYS_SERVICE_STATUS="systemctl status"
        export SYS_SERVICE_ENABLE="systemctl enable"
        export SYS_SERVICE_DISABLE="systemctl disable"
    else
        export SYS_INIT_SYSTEM="sysvinit"
        export SYS_SERVICE_CMD="service"
        export SYS_SERVICE_START="service"
        export SYS_SERVICE_STOP="service"
        export SYS_SERVICE_RESTART="service"
        export SYS_SERVICE_STATUS="service"
        export SYS_SERVICE_ENABLE="chkconfig"
        export SYS_SERVICE_DISABLE="chkconfig"
    fi
}

#############################################################################
# CONVENIENCE FUNCTIONS
#############################################################################

# Restart a service safely
restart_service() {
    local service="$1"

    if [ "$SYS_INIT_SYSTEM" = "systemd" ]; then
        systemctl restart "$service" 2>/dev/null || return 1
    else
        service "$service" restart 2>/dev/null || return 1
    fi
}

# Check if service is running
is_service_running() {
    local service="$1"

    if [ "$SYS_INIT_SYSTEM" = "systemd" ]; then
        systemctl is-active --quiet "$service" 2>/dev/null
    else
        service "$service" status 2>/dev/null | grep -q "is running"
    fi
}

export -f restart_service
export -f is_service_running

#############################################################################
# MAIL COMMAND VARIABLES
#############################################################################

derive_mail_command_info() {
    case "$SYS_MAIL_SYSTEM" in
        exim)
            export SYS_MAIL_BIN_EXIM="/usr/sbin/exim"
            export SYS_MAIL_BIN_SENDMAIL="/usr/sbin/sendmail"
            export SYS_MAIL_SPOOL="/var/spool/exim"
            export SYS_MAIL_CMD_QUEUE_COUNT="$SYS_MAIL_BIN_EXIM -bpc"
            export SYS_MAIL_CMD_QUEUE_LIST="$SYS_MAIL_BIN_EXIM -bp"
            export SYS_MAIL_CMD_QUEUE_RETRY="$SYS_MAIL_BIN_EXIM -R"
            export SYS_MAIL_CMD_QUEUE_REMOVE="$SYS_MAIL_BIN_EXIM -Mrm"
            export SYS_MAIL_CMD_TEST_ADDRESS="$SYS_MAIL_BIN_EXIM -bt"
            ;;
        postfix)
            export SYS_MAIL_BIN_POSTFIX="/usr/sbin/postfix"
            export SYS_MAIL_BIN_SENDMAIL="/usr/sbin/sendmail"
            export SYS_MAIL_SPOOL="/var/spool/postfix"
            export SYS_MAIL_CMD_QUEUE_COUNT="mailq 2>/dev/null | tail -1"
            export SYS_MAIL_CMD_QUEUE_LIST="mailq"
            export SYS_MAIL_CMD_QUEUE_RETRY="postqueue -f"
            export SYS_MAIL_CMD_QUEUE_REMOVE="postsuper -d"
            export SYS_MAIL_CMD_TEST_ADDRESS="postmap -q"
            ;;
        sendmail)
            export SYS_MAIL_BIN_SENDMAIL="/usr/sbin/sendmail"
            export SYS_MAIL_SPOOL="/var/spool/mqueue"
            export SYS_MAIL_CMD_QUEUE_COUNT="mailq 2>/dev/null | tail -1"
            export SYS_MAIL_CMD_QUEUE_LIST="mailq"
            export SYS_MAIL_CMD_QUEUE_RETRY="/usr/sbin/sendmail -q"
            export SYS_MAIL_CMD_QUEUE_REMOVE="rm -f"
            export SYS_MAIL_CMD_TEST_ADDRESS=""
            ;;
        *)
            export SYS_MAIL_BIN_EXIM=""
            export SYS_MAIL_BIN_POSTFIX=""
            export SYS_MAIL_BIN_SENDMAIL=""
            export SYS_MAIL_SPOOL=""
            export SYS_MAIL_CMD_QUEUE_COUNT=""
            export SYS_MAIL_CMD_QUEUE_LIST=""
            export SYS_MAIL_CMD_QUEUE_RETRY=""
            export SYS_MAIL_CMD_QUEUE_REMOVE=""
            export SYS_MAIL_CMD_TEST_ADDRESS=""
            ;;
    esac
}

#############################################################################
# DATABASE COMMAND VARIABLES
#############################################################################

derive_database_command_info() {
    case "$SYS_DB_TYPE" in
        mysql)
            # MySQL or MariaDB CLI commands
            export SYS_DB_CLI_COMMAND="/usr/bin/mysql"
            export SYS_DB_DUMP_COMMAND="/usr/bin/mysqldump"
            export SYS_DB_ADMIN_COMMAND="/usr/bin/mysqladmin"
            export SYS_DB_CHECK_COMMAND="/usr/bin/mysqlcheck"
            export SYS_DB_REPAIR_COMMAND="/usr/bin/mysqlcheck --repair --all-databases"
            export SYS_DB_OPTIMIZE_COMMAND="/usr/bin/mysqlcheck --optimize --all-databases"
            export SYS_DB_STATUS_COMMAND="$SYS_DB_CLI_COMMAND -e 'SHOW STATUS' 2>/dev/null"
            export SYS_DB_SHOW_DATABASES="$SYS_DB_CLI_COMMAND -e 'SHOW DATABASES' 2>/dev/null"
            export SYS_DB_SHOW_TABLES="$SYS_DB_CLI_COMMAND DATABASE -e 'SHOW TABLES' 2>/dev/null"
            ;;
        postgresql)
            # PostgreSQL CLI commands
            export SYS_DB_CLI_COMMAND="/usr/bin/psql"
            export SYS_DB_DUMP_COMMAND="/usr/bin/pg_dump"
            export SYS_DB_ADMIN_COMMAND="/usr/bin/pg_isready"
            export SYS_DB_CHECK_COMMAND="/usr/bin/pg_check"
            export SYS_DB_REPAIR_COMMAND="VACUUM FULL ANALYZE"
            export SYS_DB_OPTIMIZE_COMMAND="ANALYZE"
            export SYS_DB_STATUS_COMMAND="/usr/bin/pg_isready"
            export SYS_DB_SHOW_DATABASES="$SYS_DB_CLI_COMMAND -l"
            export SYS_DB_SHOW_TABLES="$SYS_DB_CLI_COMMAND -c '\\dt'"
            ;;
        *)
            export SYS_DB_CLI_COMMAND=""
            export SYS_DB_DUMP_COMMAND=""
            export SYS_DB_ADMIN_COMMAND=""
            export SYS_DB_CHECK_COMMAND=""
            export SYS_DB_REPAIR_COMMAND=""
            export SYS_DB_OPTIMIZE_COMMAND=""
            export SYS_DB_STATUS_COMMAND=""
            export SYS_DB_SHOW_DATABASES=""
            export SYS_DB_SHOW_TABLES=""
            ;;
    esac
}

#############################################################################
# PHP VERSION PATHS - cPanel
#############################################################################

derive_cpanel_php_versions() {
    if [ "$SYS_CONTROL_PANEL" = "cpanel" ]; then
        # cPanel stores PHP versions in /opt/cpanel/ea-phpXX/
        export SYS_CPANEL_EAPHP_BASE="/opt/cpanel"
        export SYS_CPANEL_EAPHP_BINARY_PATTERN="/opt/cpanel/ea-php{VERSION}/root/usr/bin/php"
        export SYS_CPANEL_EAPHP_CONFIG_PATTERN="/opt/cpanel/ea-php{VERSION}/root/etc/php.ini"
        export SYS_CPANEL_EAPHP_FPM_PATTERN="/opt/cpanel/ea-php{VERSION}/root/etc/php-fpm.conf"

        # Domain PHP version configuration cache
        export SYS_CPANEL_USERDATA_DIR="/var/cpanel/userdata"
        export SYS_CPANEL_DOMAIN_CONFIG_PATTERN="/var/cpanel/userdata/{USER}/{DOMAIN}.cache"

        # Domain to user mappings
        export SYS_CPANEL_TRUEUSERDOMAINS="/etc/trueuserdomains"
        export SYS_CPANEL_USERDATADOMAINS="/etc/userdatadomains"
        export SYS_CPANEL_RETENTIONDOMAINS="/etc/retentiondomains"
    else
        export SYS_CPANEL_EAPHP_BASE=""
        export SYS_CPANEL_EAPHP_BINARY_PATTERN=""
        export SYS_CPANEL_EAPHP_CONFIG_PATTERN=""
        export SYS_CPANEL_EAPHP_FPM_PATTERN=""
        export SYS_CPANEL_USERDATA_DIR=""
        export SYS_CPANEL_DOMAIN_CONFIG_PATTERN=""
        export SYS_CPANEL_TRUEUSERDOMAINS=""
        export SYS_CPANEL_USERDATADOMAINS=""
        export SYS_CPANEL_RETENTIONDOMAINS=""
    fi
}

#############################################################################
# PHP VERSION PATHS - Plesk
#############################################################################

derive_plesk_php_versions() {
    if [ "$SYS_CONTROL_PANEL" = "plesk" ]; then
        # Plesk stores PHP versions in /opt/plesk/php/X.Y/
        export SYS_PLESK_PHP_BASE="/opt/plesk/php"
        export SYS_PLESK_PHP_BINARY_PATTERN="/opt/plesk/php/{VERSION}/bin/php"
        export SYS_PLESK_FPM_SOCKET_DIR="/var/www/vhosts/system/{DOMAIN}/fpm"

        # Plesk version detection for log path structure
        # Pre-18.0.50: /var/www/vhosts/system/DOMAIN/logs/
        # Post-18.0.50: /var/www/vhosts/DOMAIN/logs/
        if [ -f "/usr/local/psa/version" ]; then
            plesk_version=$(cat /usr/local/psa/version 2>/dev/null | head -1 | awk '{print $1}')
            # Compare versions: 18.0.50 or newer = new structure
            if [ -n "$plesk_version" ] && [ "$(printf '%s\n' "18.0.50" "$plesk_version" | sort -V | head -n1)" = "18.0.50" ]; then
                export SYS_PLESK_LOG_STRUCTURE_VERSION="new"
            else
                export SYS_PLESK_LOG_STRUCTURE_VERSION="old"
            fi
        else
            export SYS_PLESK_LOG_STRUCTURE_VERSION="unknown"
        fi
    else
        export SYS_PLESK_PHP_BASE=""
        export SYS_PLESK_PHP_BINARY_PATTERN=""
        export SYS_PLESK_FPM_SOCKET_DIR=""
        export SYS_PLESK_LOG_STRUCTURE_VERSION=""
    fi
}

#############################################################################
# PHP VERSION PATHS - InterWorx
#############################################################################

derive_interworx_php_versions() {
    if [ "$SYS_CONTROL_PANEL" = "interworx" ]; then
        # InterWorx uses system PHP primarily, with optional alternates
        export SYS_INTERWORX_PHP_SYSTEM="/usr/bin/php"
        export SYS_INTERWORX_PHP_ALT_VERSIONS="/usr/local/php*/bin/php"

        # InterWorx domain-specific paths (within chroot)
        export SYS_INTERWORX_DOMAINS_BASE="/chroot/home/{ACCOUNT}/domains"
        export SYS_INTERWORX_DOMAIN_HTML="/chroot/home/{ACCOUNT}/domains/{DOMAIN}/html"
        export SYS_INTERWORX_DOMAIN_LOGS="/chroot/home/{ACCOUNT}/domains/{DOMAIN}/logs"
        export SYS_INTERWORX_VAR_LOGS_DIR="/chroot/home/{ACCOUNT}/var/{DOMAIN}/logs"
    else
        export SYS_INTERWORX_PHP_SYSTEM=""
        export SYS_INTERWORX_PHP_ALT_VERSIONS=""
        export SYS_INTERWORX_DOMAINS_BASE=""
        export SYS_INTERWORX_DOMAIN_HTML=""
        export SYS_INTERWORX_DOMAIN_LOGS=""
        export SYS_INTERWORX_VAR_LOGS_DIR=""
    fi
}

#############################################################################
# DOMAIN LOG PATHS - Variations
#############################################################################

derive_domain_log_paths() {
    case "$SYS_CONTROL_PANEL" in
        cpanel)
            # cPanel stores domain logs in /var/log/apache2/domlogs/
            export SYS_CPANEL_DOMLOGS_BASE="/var/log/apache2/domlogs"
            export SYS_CPANEL_DOMLOGS_PATTERN="/var/log/apache2/domlogs/{DOMAIN}"
            ;;
        plesk)
            # Plesk log paths vary by version
            if [ "$SYS_PLESK_LOG_STRUCTURE_VERSION" = "new" ]; then
                # Plesk 18.0.50+: /var/www/vhosts/DOMAIN/logs/
                export SYS_PLESK_DOMLOGS_PATTERN="/var/www/vhosts/{DOMAIN}/logs"
            else
                # Plesk <18.0.50: /var/www/vhosts/system/DOMAIN/logs/
                export SYS_PLESK_DOMLOGS_PATTERN="/var/www/vhosts/system/{DOMAIN}/logs"
            fi
            ;;
        interworx)
            # InterWorx domain logs (two possible locations depending on setup)
            export SYS_INTERWORX_DOMAIN_LOGS_DIR="/chroot/home/{ACCOUNT}/domains/{DOMAIN}/logs"
            export SYS_INTERWORX_VAR_LOGS_DIR="/chroot/home/{ACCOUNT}/var/{DOMAIN}/logs"
            ;;
        *)
            export SYS_CPANEL_DOMLOGS_BASE=""
            export SYS_CPANEL_DOMLOGS_PATTERN=""
            export SYS_PLESK_DOMLOGS_PATTERN=""
            export SYS_INTERWORX_DOMAIN_LOGS_DIR=""
            export SYS_INTERWORX_VAR_LOGS_DIR=""
            ;;
    esac
}

#############################################################################
# MAIN DERIVATION FUNCTION
#############################################################################

derive_all_service_info() {
    derive_web_service_info
    derive_db_service_info
    derive_mail_service_info
    derive_auth_service_info
    derive_firewall_service_info
    derive_package_manager_info
    derive_init_system_info
    derive_mail_command_info
    derive_database_command_info
    derive_cpanel_php_versions
    derive_plesk_php_versions
    derive_interworx_php_versions
    derive_domain_log_paths
}

# Auto-run if sourced with detection complete
if [ -n "${SYS_DETECTION_COMPLETE:-}" ]; then
    derive_all_service_info
fi
