#!/bin/bash

# Short Description :Compatibility check for imunify360/ImunifyAV
# Description       :Checks compatibility for imunify360/ImunifyAV installation
# Copyright         :Cloud Linux Zug GmbH
# License           :Cloud Linux Commercial License

# Do not edit/move/reformat this line except for actual version bump
# it is used by old versions of deploy scripts to check for update
version="1.4"

package="imunify360-firewall"
readonly imunify360="imunify360-firewall"
readonly imunify_av="imunify-antivirus"


OS_RELEASE_INFO=/etc/os-release
set -o pipefail

exit_with_error()
{
    echo -e "$@"
    exit 1
}

set_panel_detection_path()
{
    readonly CPANEL_BIN="/usr/local/cpanel/cpanel"
    readonly DA_BIN="/usr/local/directadmin/directadmin"
    readonly PLESK_BIN="/usr/sbin/plesk"
    readonly INTEGRATION_CONF_PATH="/etc/sysconfig/imunify360/integration.conf"
}

detect_python()
{
    # python executable is not present in CentOS 8
    if hash python2 2>/dev/null; then
        PYTHON=python2
        CONFIG_PARSER="ConfigParser"
    elif hash python3 2>/dev/null; then
        PYTHON=python3
        CONFIG_PARSER="configparser"
    else
        exit_with_error "Neither python2 nor python3 executables found"
    fi
}

detect_panel()
{
    # note: keep the panel test order in sync with agent's get_hosting_panel(),
    #   to avoid detecting conflicting panels in agent vs. the deploy script
    echo -n "PANEL="
    PANEL=""
    if [ -f "$INTEGRATION_CONF_PATH" ] ; then
        PANEL="generic"
    elif [ -f "$PLESK_BIN" ]; then
        PANEL="plesk"
    elif [ -f "$CPANEL_BIN" ]; then
        PANEL="cpanel"
    elif [ -f "$DA_BIN" ]; then
        PANEL="directadmin"
    else
        exit_with_error "$PRODUCT has not detected any compatible hosting panel as well as integration.conf file to run the installation without a panel. \
Please, follow the instructions on $STAND_ALONE_URL"
    fi
    echo $PANEL
}

populate_os_release_vars()
{
    # shellcheck source=/etc/os-release
    [ -f "$OS_RELEASE_INFO" ] && source "$OS_RELEASE_INFO"
}

detect_ostype()
{
    echo -n "ostype="
    if [ ! -f "$OS_RELEASE_INFO" ]; then
        ostype=centos
    else
        populate_os_release_vars
        if echo "$ID" "$ID_LIKE" | grep debian >/dev/null
        then
            ostype=debian
        else
            ostype=centos
        fi
    fi
    echo $ostype
}

detect_cloudways_environment() {
    hostname=$(hostname -f)
    lowercase_hostname=$(echo "$hostname" | tr '[:upper:]' '[:lower:]')

    if echo "$lowercase_hostname" | grep -Eq "\.cloudwaysapps\.com|cloudwaysstagingapps\.com"; then
        is_cloudways=true
        echo "Cloudways environment detected"
    elif [ -f /usr/local/sbin/apm ]; then
        if /usr/local/sbin/apm info | grep -q "Cloudways"; then
            is_cloudways=true
            echo "Cloudways environment detected"
        else
            is_cloudways=false
        fi
    else
        is_cloudways=false
    fi
}

is_ubuntu()
{
    populate_os_release_vars
    [ "$ID" == "ubuntu" ]
}

is_debian()
{
    populate_os_release_vars
    [ "$ID" == "debian" ]
}

UNSUPPORTED_OS_MSG="You are running an unsupported OS. $PRODUCT supports only x86_64 processors."

check_debian_release()
{
    populate_os_release_vars

    if is_debian && ([ "$VERSION_ID" -lt 10 ] || [ "$VERSION_ID" -gt 13 ])
    then
        exit_with_error "You are running unsupported version of debian based OS. $PRODUCT supports only Debian [10, 11, 12, 13]"
    fi
    if is_ubuntu && [ "$VERSION_ID" != 16.04 ] && [ "$VERSION_ID" != 18.04 ] && [ "$VERSION_ID" != 20.04 ] && [ "$VERSION_ID" != 22.04 ] && [ "$VERSION_ID" != 24.04 ]
    then
        exit_with_error "You are running unsupported version of debian based OS. $PRODUCT supports only Ubuntu 16.04, 18.04, 20.04, 22.04 and 24.04"
    fi

    if [ "$(uname -m)" != x86_64 ]
    then
        exit_with_error "$UNSUPPORTED_OS_MSG"
    fi
}

check_centos_release()
{
    rpm -q --whatprovides redhat-release > /dev/null 2>&1
    check_exit_code 0 "There is no package providing /etc/redhat-release, please install redhat-release or centos-release first"

    ARCH=$(uname -i)
    if [ -z "$ARCH" ] || [ "$ARCH" = "unknown" ]; then
        ARCH=$(uname -m)
    fi

    # handle 32bit xen with x86_64 host kernel
    if (! rpm -q glibc.x86_64 > /dev/null 2>&1) || [ "$ARCH" != "x86_64" ] ; then
        exit_with_error "$UNSUPPORTED_OS_MSG"
    fi

    check_centos_compatible
    check_virtuozzo_compatible
}

check_virtuozzo_compatible()
{
    if [ -f /proc/vz/vestat ]; then
        if version "$(uname -r)" -lt "$VZ_VERSION_BRIEF"; then
            echo "You are inside VZ."
            echo "Virtuozzo 7 with kernel $VZ_VERSION_LONG or later has support for ipset in Containers."
            exit_with_error "Please upgrade your OpenVZ hypervisor kernel version to $VZ_VERSION_LONG or later."
        fi
    fi
}

check_centos_compatible()
{
    local os_version="${1:-$(rpm --eval '%{rhel}')}"
    # shellcheck disable=SC2015
    [ "${os_version}" -lt 11 ] 2>/dev/null && [ "${os_version}" -gt 6 ] || \
        exit_with_error "Only CentOS/CloudLinux 7, 8, 9 and 10 are supported at the moment, but got os_version='${os_version}'"
}

check_exit_code() { if [ $? -ne "$1" ]; then exit_with_error "$2"; fi; }

check_debian_pkg_presence()
{
    test "$(dpkg-query --show --showformat='${db:Status-Status}\n' "$1" 2>/dev/null)" = "installed"
}

check_centos_pkg_presence()
{
    rpm --query "$1" >/dev/null
}

check_ipset_compatibility() {
    local config_file="/boot/config-$(uname -r)"

    if [[ ! -f "$config_file" ]]; then
        return 0
    fi

    if grep -Eq "^CONFIG_IP_SET=[ym]" "$config_file"; then
        return 0
    fi

    exit_with_error "ipset module not found"
}

check_iptables_compatibility() {
    local config_file="/boot/config-$(uname -r)"

    if [[ ! -f "$config_file" ]]; then
        return 0
    fi

    if grep -Eq "^CONFIG_IP_NF_IPTABLES=[ym]" "$config_file"; then
        return 0
    fi
    if grep -Eq "^CONFIG_NF_TABLES=[ym]" "$config_file"; then
        return 0
    fi

    exit_with_error "iptables modules not found"
}

version()
{
    local lhs=$1
    local op=$2
    local rhs=$3

    case $op in
        -lt) test "$(echo -e "$lhs\\n$rhs" | sort --version-sort | head -1)" = "$lhs" && \
            test "$lhs" != "$rhs"
            return $?
        ;;
        *) echo "function version(): operator $op is not supported."
            return 2
        ;;
    esac
}

check_integration_conf()
{
#
# Check whether $INTEGRATION_CONF_PATH is sufficiently valid to continue the installation, exit with an error message otherwise
#
# Globals:
#  Uses (reads) $INTEGRATION_CONF_PATH;
#  Populates (writes) $PYTHON, $CONFIG_PARSER and uses them to parse $INTEGRATION_CONF_PATH ini-file
#
    detect_python
    # sanity check: the integration.conf is a valid ini-like file
    $PYTHON -c "from $CONFIG_PARSER import ConfigParser; conf = ConfigParser(); conf.read('$INTEGRATION_CONF_PATH')" 2>/dev/null
    check_exit_code 0 "syntax error in $INTEGRATION_CONF_PATH \
Read the manual $STAND_ALONE_URL on how to create a valid config file.
"
    # sanity check: ui_path should be present in the config
    local ui_path="$($PYTHON -c "from $CONFIG_PARSER import ConfigParser; conf = ConfigParser(); conf.read('$INTEGRATION_CONF_PATH'); print(conf.get('paths', 'ui_path'))" 2>/dev/null)"
    check_exit_code 0 "$PRODUCT has detected $INTEGRATION_CONF_PATH file from the stand-alone version of $PRODUCT. \
Stand-alone version requires \"ui_path\" parameter specified in the $INTEGRATION_CONF_PATH. \
Read the manual $STAND_ALONE_URL on how to create a valid config file.
"
    # ui_path must not be empty
    if [ -z "$ui_path" ]; then
        exit_with_error "Could not get ui_path from $INTEGRATION_CONF_PATH. UI will not be installed. \
Please ensure that you have provided ui_path in $INTEGRATION_CONF_PATH \
More details is at $STAND_ALONE_URL."
    # even if ui_path doesn't refer to a directory (first install),
    # its parent directory must exist
    elif [ ! -d "$ui_path" ]; then
        # first install
        mkdir -m 0700 "$ui_path"
        check_exit_code 0 "An error occurred during creating $ui_path directory. \
Possibly parent directory doesn't exist or path point to file"
    # symlinks are not supported (current behavior)
    elif [[ -L "$ui_path" ]]; then
        exit_with_error "ui_path specified in $INTEGRATION_CONF_PATH file $ui_path points to an existing symlink. \
Installation is aborted, to avoid overwriting it. \
ui_path must point to an empty web directory. More details is at $STAND_ALONE_URL."
    # ui_path dir must be empty or point to an existing imunify installation;
    # use bin/execute.py as a heuristic for detecting the agent install
    elif [[ -n "$(ls -A "$ui_path" 2>/dev/null)" ]] && [[ ! -e "$ui_path/bin/execute.py" ]]; then
        exit_with_error "ui_path specified in $INTEGRATION_CONF_PATH file $ui_path points to a non-empty directory. \
Installation is aborted, to avoid overwriting data in it. \
ui_path must point to an empty web directory. More details is at $STAND_ALONE_URL."
    fi

    # sanity check: panel_info should be present in the config
    $PYTHON -c "from $CONFIG_PARSER import ConfigParser; conf = ConfigParser(); conf.read('$INTEGRATION_CONF_PATH'); print(conf.get('integration_scripts', 'panel_info'))" 2>/dev/null
    if [ $? -ne "0" ]; then
        echo "WARNING: integration_scripts.panel_info field will be mandatory soon, please refer to [documentation](https://docs.imunify360.com/control_panel_integration/#specifying-panel-information) and fill it!"
    else
        # sanity check: panel_info must be a valid json with name and version fields in data object
        local panel_info=$($PYTHON -c "from $CONFIG_PARSER import ConfigParser; conf = ConfigParser(); conf.read('$INTEGRATION_CONF_PATH'); print(conf.get('integration_scripts', 'panel_info'))" 2>/dev/null)
        $panel_info | $PYTHON -c 'import sys,json; d=json.load(sys.stdin); print("Panel info:", d["data"]["name"], d["data"]["version"]);'
        check_exit_code 0 "panel_info script should be executable and return valid json with name and version fields in data object. Please refer to the [documentation](https://docs.imunify360.com/control_panel_integration/#specifying-panel-information)."
    fi
}


check_users() {
    CHECK_GROUPS="ossec"
    CHECK_USERS="ossec ossecr ossecm ossece"

    SYS_GID_MAX=$(awk '/^SYS_GID_MAX/ {print $2}' /etc/login.defs)
    SYS_UID_MAX=$(awk '/^SYS_UID_MAX/ {print $2}' /etc/login.defs)

    # detect SYS_GID_MAX, SYS_UID_MAX indirectly (Ubuntu 16.04)
    GID_MIN=$(awk '/^GID_MIN/ {print $2}' /etc/login.defs)
    UID_MIN=$(awk '/^UID_MIN/ {print $2}' /etc/login.defs)
    if [ "$SYS_GID_MAX" = "" -a "$GID_MIN" != "" ]; then
        SYS_GID_MAX=$((GID_MIN - 1))
    fi
    if [ "$SYS_UID_MAX" = "" -a "$UID_MIN" != "" ]; then
        SYS_UID_MAX=$((UID_MIN - 1))
    fi

    for grp in $CHECK_GROUPS; do
        gid=$(getent group $grp 2> /dev/null | cut -d ':' -f 3)
        if [ -z "$gid" ]; then
            gid='-1'
        fi
        if [ "$SYS_GID_MAX" != "" ]; then
            if [ "$gid" -gt "$SYS_GID_MAX" ]; then
                exit_with_error "Non-system group $grp already exists"
            fi
            elif [ "$gid" != "-1" ]; then
            exit_with_error "Group $grp already exists"
        fi
    done
    for usr in $CHECK_USERS; do
        uid=$(id -u "$usr" 2>/dev/null || echo -1)
        if [ "$SYS_UID_MAX" != "" ]; then
            if [ "$uid" -gt "$SYS_UID_MAX" ]; then
                exit_with_error "Non-system user $usr already exists"
            fi
            elif [ "$uid" != "-1" ]; then
            exit_with_error "User $usr already exists"
        fi
    done
}

# Main execution starts here
if [[ "$package" = "$imunify360" ]]; then
    # Virtuozzo 7 with kernel 3.10.0 or later has support for ipset in Container
    VZ_VERSION_LONG=3.10.0-327.10.1.vz7.12.8
    # Inside VZ version is provided without release
    VZ_VERSION_BRIEF=3.10.0
fi

# Initialize variables
# Parse command line arguments
while [ "$1" != "" ]; do
    case $1 in
        --$imunify360 )
            ;;
        --$imunify_av )
            package=imunify_av
            ;;
    esac
    shift
done

if [[ "$package" = "$imunify360" ]]; then
    PRODUCT="Imunify360"
    STAND_ALONE_URL="https://docs.imunify360.com/control_panel_integration/#introduction"
fi

# Run compatibility checks
detect_ostype
check_${ostype}_release

detect_cloudways_environment
echo "is_cloudways=$is_cloudways"

set_panel_detection_path
echo "INTEGRATION_CONF_PATH=$INTEGRATION_CONF_PATH"

detect_panel
if check_${ostype}_pkg_presence "$package" >/dev/null; then
    echo "$package already installed."
    exit 0
fi

if [[ "$package" = "$imunify360" ]]; then
    check_users

    check_ipset_compatibility
    check_iptables_compatibility
fi
# For generic panel, check integration.conf
if [ "$PANEL" = "generic" ] && [ "$is_cloudways" != "true" ]; then
    check_integration_conf
fi
echo "Compatibility check passed. System is compatible with $PRODUCT."
exit 0
