#!/usr/bin/env bash
#
#   Rackspace Managed Security: Unattended installation script
#   Racksack version: 0.11.28
#   ---------------------------------------------------------------------------
#
#   This script performs an unattended installation of security agents.
#
#   IMPORTANT NOTES
#
#     * This script may require adjustment to conform to your server
#       configuration. Please review this script and test it on a server
#       before using it to install the agents on multiple servers.
#
#     * This script contains confidential agent registration keys. Please
#       keep this information safe from unauthorized users.
#

# =============================================================================
# Require root privs
# =============================================================================

if [[ $(whoami) != "root" ]]; then
  echo "This script requires root privileges. Please re-run with sudo."
  exit 1
fi

# =============================================================================
# Variables
# =============================================================================

if [ -z "$TMPDIR" ]; then
    TMPDIR="/opt"
fi

OUTPUT=''

DIST_INFO=$(cat /etc/*-release)

PACKAGE_DIR=$(mktemp -d ${TMPDIR}/agent-packages-XXXX)

# =============================================================================
# Helpers
# =============================================================================

# Args: (NONE)
_echo_ok() {
    echo " [OK]"
}

# Args: (NONE)
_echo_warn() {
    echo " [WARN]"
}

# Args: (NONE)
_echo_failed() {
    echo " [FAILED]"
}

# Args: (NONE)
_cleanup() {
    echo -n "[*] Cleaning up..."
    _try_exec rm -rf "$PACKAGE_DIR"
}

# Args: (command)
_try_exec() {
    # NOTE: Declare the local ahead of time to avoid clobbering $?
    local CMD_STDOUT
    CMD_STDOUT=$("${@}" 2>&1)

    if [ $? -ne 0 ]; then
        _echo_failed
        # add command and output for display later
        OUTPUT="$OUTPUT"$'\n\t'"${*}"$'\n\t\t'"$CMD_STDOUT"
        return 1
    fi

    _echo_ok
}

# Args: (command)
_try_exec_ignore_errors() {
    # NOTE: Declare the local ahead of time to avoid clobbering $?
    local CMD_STDOUT
    CMD_STDOUT=$("${@}" 2>&1)

    _echo_ok

    if [ $? -ne 0 ]; then
        echo "Ignoring last command's errors; stdout:"
        echo "$CMD_STDOUT"
        echo
    fi
}

# Args: (command)
_retry_once_before_failing() {
    # NOTE: Declare the local ahead of time to avoid clobbering $?
    local CMD_STDOUT
    CMD_STDOUT=$("${@}" 2>&1)

    if [ $? -ne 0 ]; then
        echo -n "[RETRYING]"
        # add command and output for display later
        OUTPUT="$OUTPUT"$'\n\t'"${*}"$'\n\t\t'"$CMD_STDOUT"

        # Wait some arbitrary amount of time before retrying
        sleep 20
        _try_exec "${@}"
        return $?
    fi

    _echo_ok
}

# Args: (package_path, digest)
_check_digest() {
    local DIGEST
    DIGEST=$(sha256sum "$1" | grep --only-matching -m 1 '^[0-9a-f]*')

    if [ "$DIGEST" = "$2" ]; then
        _echo_ok
        return 0
    else
        _echo_failed
        return 1
    fi
}

# Args: (package_path, pubkey_path)
_check_detached_sig() {
    _try_exec gpg -q --no-default-keyring --keyring "$2" --verify "$1".asc "$1"
}

# Args: (NONE)
_check_and_wait_for_yum_lock() {
    local MAX_ATTEMPTS=5
    local TIMEOUT=10
    local ATTEMPT=0

    while [[ $ATTEMPT < $MAX_ATTEMPTS ]]
    do
        if [ -e /var/run/yum.pid ] && ps -p "$(cat /var/run/yum.pid)" > /dev/null; then
            echo "      [*] Yum already running, sleeping $TIMEOUT seconds..."
            sleep $TIMEOUT
        fi
        ATTEMPT=$(( ATTEMPT + 1 ))
        TIMEOUT=$(( TIMEOUT * 2))
    done
    echo
}

# Args: (NONE)
_check_and_wait_for_dpkg_lock() {
    local MAX_ATTEMPTS=5
    local TIMEOUT=10
    local ATTEMPT=0

    while [[ $ATTEMPT < $MAX_ATTEMPTS ]]
    do
        if fuser /var/lib/dpkg/lock >/dev/null 2>&1; then
            echo "      [*] Dpkg/apt already running, sleeping $TIMEOUT seconds..."
            sleep $TIMEOUT
        fi
        ATTEMPT=$(( ATTEMPT + 1 ))
        TIMEOUT=$(( TIMEOUT * 2))
    done
    _echo_ok
}

_os_version_information() {
    echo "[*] Get OS Version Information..."
    readonly distro_check=$(lsb_release -ds 2>/dev/null || \
                            cat /etc/*release 2>/dev/null || \
                            cat /usr/lib/os-release 2>/dev/null)
    readonly distro=$(echo "$distro_check" | head -n2)
    readonly distro_name=$(echo "$distro" | grep -Po 'CentOS|Red Hat|Amazon|Oracle|Ubuntu')
    readonly distro_version=$(echo "$distro" | grep -Po '[.[:digit:]]*')
    readonly distro_kernel=$(uname -r)

    if [ ! "$distro_version" ] || [ ! "$distro_name" ]; then
        echo "   [*] Failed to get release info"
        return 1
    fi
}

# Args: (NONE)
_output_os_information() {
    echo "$distro_name" "$distro_version"
    echo "Kernel: $distro_kernel"
    echo -n "Selinux: "
    if which getenforce >/dev/null 2>&1;
    then
        getenforce;
    else
        echo "not installed";
    fi
}
# =============================================================================
# Determine package type
# =============================================================================

PACKAGING=''

# check for apt, but discard stdout (path to apt)
apt_exists() { command -v apt 1> /dev/null; }

# check for yum, but discard stdout (path to yum)
yum_exists() { command -v yum 1> /dev/null; }

if [ -e /etc/debian_version ] && apt_exists; then
    PACKAGING=debian
elif yum_exists; then
    PACKAGING=rpm
else
    echo "Could not determine distro type."
    echo
    lsb_release -a
    cat /etc/*release
    cat /etc/issue*
    exit 1
fi

# =============================================================================
# Debian Functions
# =============================================================================

if [[ "${PACKAGING}" == "debian" ]]; then

PACKAGE_EXT='.deb'

# Args: (PACKAGE_PATH)
install_package_and_deps(){
    echo -n "   [*] Checking for dpkg lock..."
    _check_and_wait_for_dpkg_lock
    if dpkg --compare-versions "$(dpkg -s apt | awk '/^Version/ {print $2}')" ge 1.1
    then
        echo -n "   [*] Installing package and dependencies..."
        _try_exec apt-get -y install  "$@"
    else
        echo -n "   [*] Installing the package..."
        _try_exec dpkg -EGi --force-depends "$@"
        echo -n "   [*] Installing package dependencies..."
        _try_exec apt-get install -yf
    fi
}

CLOUDPASSAGE_KEY='7c58f424952bf5b27a7b4ebecc2f1ab1'
CLOUDPASSAGE_REPO_KEY_URL='https://production.packages.cloudpassage.com/cloudpassage.packages.key'
CLOUDPASSAGE_REPO_KEY_DIGEST='1f5461191a296736146a21cc51216c2f71218630bab26ea8922512299990d9c5'

# Args: (KEY_PATH)
_install_cloud_passage_for_distro() {
    local KEY_PATH="$1"

    echo -n "   [*] Adding the CloudPassage repository..."
    echo 'deb https://production.packages.cloudpassage.com/debian debian main' > \
        /etc/apt/sources.list.d/cloudpassage.list

    _echo_ok

    echo -n "   [*] Importing public key..."
    _try_exec apt-key add "$KEY_PATH"

    echo -n "   [*] Updating apt repositories..."
    _try_exec apt-get update

    echo -n "   [*] Installing the Halo agent..."
    _try_exec apt-get -y install cphalo
}

CROWD_STRIKE_4_URL="https://packages.rackspace.security/crowdstrikev4/falcon-sensor_5.28.0-9205_amd64.deb?AWSAccessKeyId=AKIAIAEAOLV4VHXGYWDQ&Signature=qzAPvq5NMgf1GI%2Bc9H01%2FABO0m4%3D&Expires=1593370668"
CROWD_STRIKE_4_DIGEST="c40661c75413a54355e5e844d9eb4b704e5d7972ed8d86997f58766bf20b1042"
CROWD_STRIKE_4_CCID="79C6F52B35BE4FEB8D29F0A8CA8C4230-5E"

# Make sure package configuration won't block the install/upgrade process
export DEBIAN_FRONTEND=noninteractive

echo -n "   [*] Manually install Armor Anywhere agent dependencies..."
_check_and_wait_for_dpkg_lock
apt-get update > /dev/null 2>&1
apt-get -y install openssl curl > /dev/null 2>&1
_echo_ok
# Args: (NONE)
_restart_rsyslog() {
    _try_exec service rsyslog restart
}

fi  # end if PACKAGING==debian

# =============================================================================
# Redhat Functions
# =============================================================================

if [[ "${PACKAGING}" == "rpm" ]]; then

PACKAGE_EXT='.rpm'

install_package_and_deps(){
    echo -n "   [*] Checking for yum lock..."
    _check_and_wait_for_yum_lock

    echo -n "   [*] Installing the package..."
    # disable scaleft repo if it exists due to failures
    if [[ $(yum repolist) == *ScaleFT* ]];
    then
        _try_exec yum --disablerepo=scaleft localinstall -y "$PACKAGE_PATH"
    else
        _try_exec yum localinstall -y "$PACKAGE_PATH"
    fi
}

CLOUDPASSAGE_KEY='7c58f424952bf5b27a7b4ebecc2f1ab1'
CLOUDPASSAGE_REPO_KEY_URL='https://production.packages.cloudpassage.com/cloudpassage.packages.key'
CLOUDPASSAGE_REPO_KEY_DIGEST='1f5461191a296736146a21cc51216c2f71218630bab26ea8922512299990d9c5'

# Args: (KEY_PATH)
_install_cloud_passage_for_distro() {
    local KEY_PATH="$1"

    echo -n "   [*] Adding the CloudPassage repository..."
    echo -e "[cloudpassage]\nname=CloudPassage\nbaseurl=https://production.packages.cloudpassage.com/redhat/\$basearch\ngpgcheck=1" > \
        /etc/yum.repos.d/cloudpassage.repo

    _echo_ok

    echo -n "   [*] Importing CloudPassage public key..."
    _try_exec rpm --import "$KEY_PATH"

    echo -n "   [*] Installing the Halo agent..."
    _try_exec yum -y install cphalo
}
# Args: (NONE)
_restart_rsyslog() {
    if [[ $DIST_INFO =~ (Red\ Hat|CentOS).+release\ 7 ]]; then
        _try_exec /usr/bin/systemctl restart rsyslog
    else
        _try_exec service rsyslog restart
    fi
}

_specify_cs4_rpm_pkg() {
    # The Crowd Strike Kernel Sensor requires us to distinguish between
    # Redhat/CentOS 6, Redhat/CentOS 7, and Amazon Linux
    # if this is a single line, it should contain version and name, if the more
    # structured file, name is first line, version is second

    if [[ "${distro_name}" == *Amazon* ]]; then
        if [[ "${distro_version}" == '2' || "${distro_version}" == '2.'* || "${distro_version}" == '2 '* ]]; then
            CROWD_STRIKE_4_URL="https://packages.rackspace.security/crowdstrikev4/falcon-sensor-5.28.0-9205.amzn2.x86_64.rpm?AWSAccessKeyId=AKIAIAEAOLV4VHXGYWDQ&Signature=CtfokN%2B1OwpGVt0AKngyWuhu9gw%3D&Expires=1593370667"
            CROWD_STRIKE_4_DIGEST="fe5ac56bb2ec842c0fd16a9217c52ba4a52f752f70e0cd77efecde4b7466a97a"
            CROWD_STRIKE_4_CCID="79C6F52B35BE4FEB8D29F0A8CA8C4230-5E"
        else
            CROWD_STRIKE_4_URL="https://packages.rackspace.security/crowdstrikev4/falcon-sensor-5.28.0-9205.amzn1.x86_64.rpm?AWSAccessKeyId=AKIAIAEAOLV4VHXGYWDQ&Signature=GkFndSgKfNEBdubIL7lGMMY%2B5ls%3D&Expires=1593370667"
            CROWD_STRIKE_4_DIGEST="708410f02895e31a5f6e8b99cc96e8f1dddd1991743edab274a5126efd95d76e"
            CROWD_STRIKE_4_CCID="79C6F52B35BE4FEB8D29F0A8CA8C4230-5E"
        fi
    elif [[ "${distro_version}" == '8.'* ]]; then
        CROWD_STRIKE_4_URL="https://packages.rackspace.security/crowdstrikev4/falcon-sensor-5.28.0-9205.el8.x86_64.rpm?AWSAccessKeyId=AKIAIAEAOLV4VHXGYWDQ&Signature=HNBzUNtc%2B49jyUJwyn6l1LHZBXw%3D&Expires=1593370668"
        CROWD_STRIKE_4_DIGEST="d53feb8c296b5af4ee7f96da06c1613f3b3384f016272eb33c301b9bfd106945"
        CROWD_STRIKE_4_CCID="79C6F52B35BE4FEB8D29F0A8CA8C4230-5E"
    elif [[ "${distro_version}" == '7.'* ]]; then
        CROWD_STRIKE_4_URL="https://packages.rackspace.security/crowdstrikev4/falcon-sensor-5.28.0-9205.el7.x86_64.rpm?AWSAccessKeyId=AKIAIAEAOLV4VHXGYWDQ&Signature=j7jSxAYwbjfVv63HwYUzPdYllNo%3D&Expires=1593370668"
        CROWD_STRIKE_4_DIGEST="f9e37177c8cf6cb12cfd8e099882b89380c8a003715efe589188ef3f9512defd"
        CROWD_STRIKE_4_CCID="79C6F52B35BE4FEB8D29F0A8CA8C4230-5E"
    elif [[ "${distro_version}" == '6.'* ]]; then
        CROWD_STRIKE_4_URL="https://packages.rackspace.security/crowdstrikev4/falcon-sensor-5.28.0-9205.el6.x86_64.rpm?AWSAccessKeyId=AKIAIAEAOLV4VHXGYWDQ&Signature=qGPNHvNfK8VzMw%2F3SKa1WP6G128%3D&Expires=1593370667"
        CROWD_STRIKE_4_DIGEST="83e3a23dd38ae8a8528613c1bf9d364af593093b7a0079dbefd7aab95fdad571"
        CROWD_STRIKE_4_CCID="79C6F52B35BE4FEB8D29F0A8CA8C4230-5E"
    else
        echo "   [*] Unsupported distro with ${distro_name} and VERSION=${distro_version}."
        return 1
    fi
}

echo -n "   [*] Manually install Armor Anywhere agent dependencies..."
_check_and_wait_for_yum_lock
yum update -y curl > /dev/null 2>&1
fi  # end if PACKAGING==rpm

# =============================================================================
# Package installers
# =============================================================================

_start_crowdstrike_4() {
    echo -n "   [*] Starting CrowdStrike agent..."

    if [[ $DIST_INFO =~ (Red\ Hat|CentOS).+release\ 7 ]]; then
        _try_exec systemctl start falcon-sensor
    else
        _try_exec service falcon-sensor start
    fi
}

# Args: (NONE)
_install_crowd_strike_4() {

    local CS4_ERROR

    echo "[*] Installing CrowdStrike4..."

    if [[ "$PACKAGE_EXT" == ".rpm" ]]; then
        _specify_cs4_rpm_pkg
        if [ $? -ne 0 ]; then return 1; fi
    fi

    local PACKAGE_PATH="${PACKAGE_DIR}/falcon-sensor${PACKAGE_EXT}"

    echo -n "   [*] Downloading the CrowdStrike4 package..."
    _try_exec curl -fsS -o "$PACKAGE_PATH" "${CROWD_STRIKE_4_URL}"
    if [ $? -ne 0 ]; then return 1; fi

    echo -n "   [*] Verifying the package..."
    _check_digest "$PACKAGE_PATH" "$CROWD_STRIKE_4_DIGEST"
    if [ $? -ne 0 ]; then return 1; fi

    install_package_and_deps "${PACKAGE_PATH}"
    if [ $? -ne 0 ]; then return 1; fi

    # With CrowdStrike FalconHost v4.x, we set the CCID (checksum customer ID),
    # which is the CID followed by a hyphen and two hex digits (one byte). This
    # is stored as the "crowdstrike agent registration key" in
    # customer-service.
    # Setting the CCID must be done after installation, and before starting the
    # service, so that the agent can check in with CrowdStrike correctly.
    # Using the `-f` option is required, or the installer will complain that it
    # wasn't specified.
    echo -n "   [*] Setting CrowdStrike checksum CID..."
    _try_exec /opt/CrowdStrike/falconctl -s -f --cid="${CROWD_STRIKE_4_CCID}"

    # start the service with whichever system init is present
    _start_crowdstrike_4

    sleep 5

    if [[ ! $(pgrep falcon-sensor) ]]; then
        CS4_ERROR=1
    fi

    # Give CrowdStrike time to register and retrieve its AID
    echo "   [*] Waiting 10s to register with CrowdStrike..."
    sleep 10

    # Display relevant agent info
    echo "   [*] Agent info: $(/opt/CrowdStrike/falconctl -g --cid --aid)"

    # Display kernel info
    echo "   [*] Kernel info: $(uname -r)"

    return $CS4_ERROR
}

# Args: (NONE)
_install_cloud_passage() {
    local KEY_PATH="$PACKAGE_DIR/cloudpassage.packages.key"
    local CP_ERROR

    echo "[*] Installing CloudPassage..."

    echo -n "   [*] Downloading CloudPassage public key..."
    _try_exec curl -fsS -o "$KEY_PATH" "${CLOUDPASSAGE_REPO_KEY_URL}"
    if [ $? -ne 0 ]; then return 1; fi

    echo -n "   [*] Verifying the downloaded key..."
    _check_digest "$KEY_PATH" "${CLOUDPASSAGE_REPO_KEY_DIGEST}"
    if [ $? -ne 0 ]; then return 1; fi

    _install_cloud_passage_for_distro "${KEY_PATH}"
    if [ $? -ne 0 ]; then return 1; fi

    echo -n "   [*] Configuring the agent..."
    _try_exec /opt/cloudpassage/bin/configure --agent-key="${CLOUDPASSAGE_KEY}" --read-only=true
    if [ $? -ne 0 ]; then CP_ERROR=1; fi

    # NOTE: Use restart rather than start; all the other steps are idempotent,
    # and this one must be as well. If the daemon isn't already running,
    # restart will still produce a 0 exit code.
    echo -n "   [*] Starting the agent..."
    _try_exec service cphalod restart
    if [ $? -ne 0 ]; then CP_ERROR=1; fi

    return $CP_ERROR
}

ARMOR_LICENSE_KEY="BMGK2-HC2J3-TDX7H-93VK6-HX88D"

_get_tags() {
    local armor_data_file="/etc/armor/core.data"
    local private_key=$(grep -oP  '(?<="privateKey":")[^"]*' ${armor_data_file})
    local account_id=$(grep -oP  '(?<="accountId":")[^"]*' ${armor_data_file})
    local coreinstance_id=$(grep -oP  '(?<="coreInstanceId":")[^"]*' ${armor_data_file})

    if which curl >/dev/null; then
        local RESPONSE=$(curl -s -H "Authorization: ${private_key}" -H "X-Accountid: ${account_id}" -H "X-Coreinstanceid: ${coreinstance_id}" -H 'Content-Type: application/json' https://agent.api.secure-prod.services/agent/tags/)
    else
        local RESPONSE=$(wget -q -O- --header="Authorization: ${private_key}" --header="X-Accountid: ${account_id}" --header="X-Coreinstanceid: ${coreinstance_id}" --header='Content-Type: application/json' https://agent.api.secure-prod.services/agent/tags/)
    fi
    echo "${RESPONSE}"
}

_verify_tags() {
    local expected_tags=$1
    local current_tags=$(_get_tags)
    local all_current_keys=($(echo "${current_tags}" | grep -oP '(?<="Key":")[^"]*'))
    local all_current_values=($(echo "${current_tags}" | grep -oP '(?<="Value":")[^"]*'))

    IFS="," read -r -a expected_tags_list <<< "${expected_tags}"
    unset IFS
    for expected_tag_item in "${expected_tags_list[@]}"; do
        IFS="=" read -r -a tag_with_value <<< "${expected_tag_item}"
        unset IFS
        local key="${tag_with_value[0]}"
        local value="${tag_with_value[1]}"
        if [[ " ${all_current_keys} " =~ " ${key} " && " ${all_current_values} " =~ " ${value} " ]]; then
            # No-Op
            :
        else
            return 1
        fi
        return 0
    done
}

_get_instance_id() {
    local INSTANCE_ID=`curl -s -H "Metadata: true" "http://169.254.169.254/metadata/instance/compute/vmId?api-version=2019-08-15&format=text"`

    echo "${INSTANCE_ID}"
}

_fix_armor_cronjob_output() {
    local CRON_FILE=/etc/cron.d/armor-job-SUPERVISOR_TASKS
    sed -i 's/get-tasks$/get-tasks >\/dev\/null 2>\&1/' ${CRON_FILE}
    return $?
}

_wait_for_active_av() {
    local MAX_ATTEMPTS=5
    local TIMEOUT=10
    local ATTEMPT=0

    while [[ $ATTEMPT < $MAX_ATTEMPTS ]]
    do
        local CORE_VERSION=$(/opt/ds_agent/dsa_query --cmd GetComponentInfo | grep 'CORE.version' | cut -d' ' -f2)
        if [[ "${CORE_VERSION}" == "" ]]; then
            echo "   [!] Trend AV module not active yet, retrying in ${TIMEOUT} seconds..."
            sleep ${TIMEOUT}
        else
            echo "   [*] Trend AV module active with CORE version ${CORE_VERSION}"
            return 0
        fi
        ATTEMPT=$(( ATTEMPT + 1 ))
        TIMEOUT=$(( TIMEOUT * 2 ))
    done

    return 1
}

_test_antivirus_event() {
    echo "[*] Running Antivirus Test"
    av_info=$(/opt/ds_agent/dsa_query --cmd GetComponentInfo)
    echo "   [*] AV info: ${av_info}"
    echo -n "   [*] Downloading Antivirus Test file"
    eicar_path="${PACKAGE_DIR}/826372d950ab06689d0bc41aef630d1248c0e489.com"
    eicar_url="https://packages.rackspace.security/tests/antivirus/826372d950ab06689d0bc41aef630d1248c0e489.com"
    _try_exec_ignore_errors curl -fsS -o "${eicar_path}" "${eicar_url}"
    sleep 10
    if [ -f "${eicar_path}" ]; then
        echo "   [!] EICAR test file still exists, retrying AV test."
        rm -f "${eicar_path}"
        sleep 20
        av_info=$(/opt/ds_agent/dsa_query --cmd GetComponentInfo)
        echo "   [*] AV info: ${av_info}"
        _try_exec_ignore_errors curl -fsS -o "${eicar_path}" "${eicar_url}"
        sleep 5
        if [ -f "${eicar_path}" ]; then
            echo "   [!] EICAR test file was not removed from system, AV not functional."
            return 1
        fi
    fi
}

INSTANCE_ID=$(_get_instance_id)
ARMOR_CMD=/opt/armor/armor
EXPECTED_TAGS="provider_instance_id=${INSTANCE_ID}"

_install_armor() {

    echo "[*] Installing Armor..."
    curl -sSL https://agent.armor.com/latest/armor_agent.sh | bash /dev/stdin -r us-west -l ${ARMOR_LICENSE_KEY}
    if [ $? -ne 0 ]; then return 1; fi
    echo -n "   [*] Silence Armor cron job..."
    _try_exec _fix_armor_cronjob_output
    echo "   [*] Query core instance ID..."
    ${ARMOR_CMD} show db
    echo "   [*] Fetched instance ID: ${INSTANCE_ID}"
    echo -n "   [*] Tagging Armor instance..."
    _try_exec ${ARMOR_CMD} tags create-locked-tags ${EXPECTED_TAGS}
    sleep 10
    echo -n "   [*] Verifying tags were correctly set..."
    _retry_once_before_failing _verify_tags ${EXPECTED_TAGS}
    if [ $? -ne 0 ]; then
        _echo_failed
        return 1
    else
        _echo_ok
    fi
    echo -n "   [*] Installing Trend Micro sub-agent..."
    _retry_once_before_failing ${ARMOR_CMD} trend install
    if [ $? -ne 0 ]; then return 1; fi
    echo -n "   [*] Enabling Anti-Virus..."
    _retry_once_before_failing ${ARMOR_CMD} av on
    if [ $? -ne 0 ]; then return 1; fi
    echo -n "   [*] Enabling File Integrity Monitoring..."
    _retry_once_before_failing ${ARMOR_CMD} fim on auto-apply-recommendations=on
    if [ $? -ne 0 ]; then return 1; fi
    echo -n "   [*] Enabling Intrusion Prevention System..."
    _retry_once_before_failing ${ARMOR_CMD} ips detect auto-apply-recommendations=on
    if [ $? -ne 0 ]; then return 1; fi
    echo -n "   [*] Sending Trend Micro heartbeat..."
    _try_exec /opt/ds_agent/dsa_control -m
    if [ $? -ne 0 ]; then return 1; fi
    echo -n "   [*] Waiting for all Trend Micro services to be ready..."
    sleep 20
    _echo_ok
    echo -n "   [*] Schedule one-time Trend Micro recommendation scan..."
    _retry_once_before_failing ${ARMOR_CMD} trend recommendation-scan
    if [ $? -ne 0 ]; then return 1; fi
    echo -n "   [*] Schedule ongoing Trend Micro recommendation scan..."
    _retry_once_before_failing ${ARMOR_CMD} trend ongoing-recommendation-scan on
    if [ $? -ne 0 ]; then return 1; fi
    echo -n "   [*] Installing Logging sub-agent..."
    _retry_once_before_failing ${ARMOR_CMD} logging install
    if [ $? -ne 0 ]; then return 1; fi
    echo -n "   [*] Installing Vulnerability sub-agent..."
    _retry_once_before_failing ${ARMOR_CMD} vuln install
    if [ $? -ne 0 ]; then return 1; fi
    echo -n "   [*] Verify that Armor Agent is running..."
    _try_exec pgrep armor
    if [ $? -ne 0 ]; then return 1; fi
    echo -n "   [*] Verify that Trend Micro is running..."
    _try_exec pgrep ds_agent
    if [ $? -ne 0 ]; then return 1; fi
    echo -n "   [*] Verify that Qualys is running..."
    _try_exec pgrep qualys
    if [ $? -ne 0 ]; then return 1; fi
    echo -n "   [*] Verify that logging is running..."
    _retry_once_before_failing pgrep filebeat
    if [ $? -ne 0 ]; then return 1; fi
    _wait_for_active_av
    _test_antivirus_event
    if [ $? -ne 0 ]; then return 1; fi
    return 0
}

main() {
    local exit_code=0

    _os_version_information

    _install_crowd_strike_4
    local cs4_exit=$?
    ((exit_code|=cs4_exit))

    _install_cloud_passage
    local cp_exit=$?
    ((exit_code|=cp_exit))

    _install_armor
    local armor_exit=$?
    ((exit_code|=armor_exit))

    _cleanup

   if [ "$exit_code" -ne 0 ]; then
        echo
        _output_os_information
        echo
        echo "[*] OUTPUT from failed commands:"
        echo "$OUTPUT"
    fi

    exit "$exit_code"
}

main
