#!/bin/bash
# Copyright Atomicorp, Inc
# 2025

################################
# Global Variables
################################
export LANG=en_US.UTF-8
INSTALLER_VERSION=7.5.3

LOG=/root/awp-install.log
ARCH=$(uname -i)
ALT_REPO_DISABLED=0
TC_TARGET="updates.atomicorp.com/channels/asl-3.0/README"


# set the default values for the arguments
BETA=0
HTTPS_PROXY=""
HTTPS_PROXY_USERNAME=""
HTTPS_PROXY_PASSWORD=""
STANDALONE=0

# create a show_help function
function show_help() {
	echo
	echo "Atomicorp Hub Installler"
	echo "  Version: $INSTALLER_VERSION"
	echo "  Usage: $0 [options]" 
	echo
	echo "  Options:"
	echo "    --https-proxy=<URL> will set the https_proxy environment variable"
	echo "    --https-proxy-username=<PROXY_USER> will set the https_proxy_username environment variable"
	echo "    --https-proxy-password=<PROXY_PASS> will set the https_proxy_password environment variable"
	echo "    --beta will install from the beta repository"
	echo "    --install only install, do not configure"
	echo "    --standalone local install (no hub)"
	echo
}


###############################
# Functions
###############################
function app_exit {
    EXIT_CODE=$1

    # re-enable disabled repos
    if [ $ALT_REPO_DISABLED -ge 1 ]; then
        for reponame in $ALT_REPO; do
            /usr/bin/yum-config-manager --enable $reponame > /dev/null
        done
    fi

    # remove lock file
    rm -f /awp-installer.lock

    # exit
    echo
    echo "`date -u` ERROR: abnormal exit $EXIT_CODE" | tee -a $LOG
    echo
    exit $EXIT_CODE
}

function check_input {
  message=$1
  validate=$2
  default=$3

  while [ $? -ne 1 ]; do
    echo -n "$message "
    read INPUTTEXT < $INSTALL_TTY
    if [ "$INPUTTEXT" == "" -a "$default" != "" ]; then
      INPUTTEXT=$default
      return 1
    fi
    echo $INPUTTEXT | egrep -q "$validate" && return 1
    echo "Invalid input"
  done

}


rawurlencode() {
  local string="${1}"
  local strlen=${#string}
  local encoded=""

  for (( pos=0 ; pos<strlen ; pos++ )); do
     c=${string:$pos:1}
     case "$c" in
        [-_.~a-zA-Z0-9] ) o="${c}" ;;
        * )               printf -v o '%%%02x' "'$c"
     esac
     encoded+="${o}"
  done
  echo "${encoded}"
  REPLY="${encoded}"
}

function check_prexisting_reps {
	if [ -f /etc/yum.repos.d/asl.repo ]; then
		rm -f /etc/yum.repos.d/asl.repo
	fi

	if [ -f /etc/yum.repos.d/awp.repo ]; then
		rm -f /etc/yum.repos.d/awp.repo
	fi
}

function check_diskspace {
    FILESYSTEM=$1
    MINIMUM=$2
    RECOMENDED=$3

    if [[ $PKG == "deb" ]]; then
        # Ubuntu uses df with different options
        FREESMB=$(df -m ${FILESYSTEM} | awk 'NR==2 {print $4}')
    else
        SIZES=($(stat -L -f -c "%a %S" ${FILESYSTEM}))
        FREES=$((${SIZES[0]}*${SIZES[1]}))
        FREESMB=$(($FREES/1024/1024))
    fi

    echo -n "  `date -u` Freespace Check: " | tee -a $LOG 
    if [ $FREESMB -lt $RECOMENDED ]; then
        if [ $FREESMB -lt $MINIMUM ]; then
            echo "FAILURE: in order to complete installation $FILESYSTEM will need at least $MINIMUM MB free." | tee -a $LOG
            echo "Currently: $FREESMB MB free" | tee -a $LOG
            app_exit 1
        fi
        echo "Warning: $RECOMENDED GB is the recommended amount of disk space for awp-hub." | tee -a $LOG
    else 
        echo "PASS"  | tee -a $LOG
    fi
}

function check_third_party {
	# Check for 3rd party repos
	ALT_REPO=$(yum -v -C repolist |awk -F: '/Repo-id/  {print $2}' |egrep -iv "^ (asl-|atomic|base|extras|updates|tortix|cloudlinux|epel|plesk|rhel-6|EA4|r1soft|quantum|zabbix|PLESK|mysql|percona|cpanel-addons-production-feed|rack|mariadb|rhel-7|rhel-server|rhel-ha|rhel-rs|rhel-sjis)")
	RETVAL=$?

	echo -n "  `date -u` ThirdParty Repo Check: " | tee -a $LOG
	if [ $RETVAL -lt 1 ]; then
		echo -n "WARNING - Third party repos detected, Temporarily disabling."
		if [ -f /usr/bin/yum-config-manager ]; then
				ALT_REPO_DISABLED=1
				for reponame in $ALT_REPO; do
					echo "Disabling: $reponame"
					/usr/bin/yum-config-manager --disable $reponame > /dev/null
				done
		fi
	else 
		echo "PASS"
	fi

}

function check_ram {
    MIN_RAM=$1
    echo -n "  `date -u` MEM: "
    if [[ $PKG == "deb" ]]; then
        # Ubuntu uses free with different output format
        ram=$(free -m | awk '/Mem:/ {print $2}')
        swap=$(free -m | awk '/Swap:/ {print $2}')
    else
        ram=$(free | awk '/Mem:/ {print $2}')
        swap=$(free | awk '/Swap:/ {print $2}')
    fi
    
    if [ $ram -lt $MIN_RAM ]; then
        echo "FAIL - A minimum of 4G of memory is required" | tee -a $LOG
        app_exit 1
    else
        echo "PASS"
    fi
}

function check_swap {
    echo -n "  `date -u` SWAP: "
    if [[ $PKG == "deb" ]]; then
        # Ubuntu uses free with different output format
        swap=$(free -m | awk '/Swap:/ {print $2}')
    else
        swap=$(free | awk '/Swap:/ {print $2}')
    fi
    
    if [ $swap -lt 2090000 ]; then
        echo "FAIL - A minimum swap size of 2G is required for AWP." | tee -a $LOG
    else 
        echo "PASS"
    fi
}

function check_ports {
    PORT_INFO_WEBD=$(ss -tulwnp | grep -e "tcp.*:30001" | awk '{print $7}')
    re="users:.*\"(.*)\",pid=([0-9]+),fd=([0-9]+).*"
    echo -n "  `date -u` PORT-CHECK-1: "
    if [[ $PORT_INFO_WEBD =~ $re ]]; then
        if [[ ${BASH_REMATCH[1]} == "awpwebd" ]]; then
            systemctl stop awpwebd
            sleep 5s
            echo "PASS: ${BASH_REMATCH[1]} deactivated for install."
        else
            echo "FAIL: unexpected service using port 30001. Exiting..." | tee -a $LOG
            app_exit 1
        fi
    else
        echo "PASS"
    fi

    PORT_INFO_TORTIXD=$(ss -tulwnp | grep -e "tcp.*:30000" | awk '{print $7}')
    re="users:.*\"(.*)\",pid=([0-9]+),fd=([0-9]+).*"
    echo -n "  `date -u` PORT-CHECK-2: "
    if [[ $PORT_INFO_TORTIXD =~ $re ]]; then
        if [[ ${BASH_REMATCH[1]} == "tortixd" ]]; then
            systemctl stop tortixd
            sleep 5s
            echo "PASS: ${BASH_REMATCH[1]} deactivated for install."
        else
            echo "FAIL: unexpected service using port 30000. Exiting..." | tee -a $LOG
            app_exit 1
        fi
    else
        echo "PASS"
    fi
}

function check_cores {
        CORES=$(nproc)
        echo -n "  `date -u` CPU Cores ($CORES): " | tee -a $LOG
        if [[ $CORES -ge 2 ]]; then
                echo "PASS" | tee -a $LOG
        else
                echo "FAIL - A minimum of 2 cores needed, $CORES available." | tee -a $LOG
                app_exit 1
        fi

}

function check_ssl {
	echo -n "  `date -u` SSL: " | tee -a $LOG
	curl -s https://google.com >/dev/null
	RETVAL=$?
	if [ $RETVAL -eq 60 ]; then
		echo "FAILED: SSL Network failure (google.com): CA invalid" | tee -a $LOG
		app_exit 1

	elif [ $RETVAL -ne 0 ] ; then
		echo "FAILED: SSL Network failure (google.com): connection failed" | tee -a $LOG
		app_exit 1

	else
		echo "PASS" | tee -a $LOG
		
	fi
}

function check_release {
	if [ -f /etc/system-release ]; then
		RELEASE_FILE=/etc/system-release
	elif [ -f /etc/redhat-release ] ; then
		RELEASE_FILE=/etc/redhat-release
	elif [ -f /etc/os-release ]; then
        RELEASE_FILE=/etc/os-release
	else
		echo | tee -a $LOG
		echo "Error: /etc/redhat-release was not detected" | tee -a $LOG
		echo
		echo "`date -u` ERROR: could not determine release file" | tee -a $LOG
		app_exit 1
	fi

	if egrep -q "release 7" $RELEASE_FILE ; then
		DIST="el7"
		DIR=centos/7
		SUGGESTS="tortixd tortixd-mod_ssl tortix-waf tortix-mod_evasive tcpdump ansible"
		PKG=rpm
	elif egrep -q "release 8" $RELEASE_FILE ; then
		DIST="el8"
		DIR=centos/8
		SUGGESTS="wireshark-cli ansible-core certbot clamav-filesystem"
		PKG=rpm
	elif egrep -q "release 9" $RELEASE_FILE ; then
		DIST="el9"
		DIR=rocky/9
		SUGGESTS="wireshark-cli ansible-core certbot clamav-filesystem"
		PKG=rpm
	elif egrep -q "Bionic" $RELEASE_FILE && [ $STANDALONE -eq 1 ]; then
		DIST="bionic"
		DIR=ubuntu/18
		SUGGESTS=""
		PKG=deb
	elif egrep -q "Focal" $RELEASE_FILE && [ $STANDALONE -eq 1 ]; then
		DIST="focal"
		DIR=ubuntu/20
		SUGGESTS=""
		PKG=deb
	else
		echo "Error: Unable to determine distribution type. Please send the contents of $RELEASE_FILE to support@atomicorp.com" | tee -a $LOG
		echo "`date -u` ERROR: unable to determine distribution type" | tee -a $LOG
		echo 
		echo "${TITLE} Supported platforms are:"
		echo "  * RHEL/Centos 7"
		echo "  * RHEL/Rocky 8"
		echo "  * RHEL/Rocky 9"
		if [ $STANDALONE -eq 1 ]; then
			echo "  * Ubuntu 18.04 (bionic)"
			echo "  * Ubuntu 20.04 (focal)"
		fi
		echo
		app_exit 1
	fi
	echo "  `date -u` distribution determined as $DIST" | tee -a $LOG
}

function check_csf {
	if [ -d /etc/csf ]; then
		echo "WARNING: Configserver (CSF) detected. AP does not support CSF." | tee -a $LOG
		echo "CSF or other 3rd party WAF / Firewall management tools should be removed" | tee -a $LOG
		echo "before installing AP." | tee -a $LOG



		if [ ! $AUTO ]; then
			check_input "  Would you like to remove csf? (yes/no) [Default: yes]" "yes|no" "yes"
			if [ "$INPUTTEXT" == "yes" ]; then
				if [ -f /etc/csf/uninstall.sh ]; then
					/etc/csf/uninstall.sh
				fi
			else
				check_input "  Do you wish to continue? (yes/no) [Default: no]" "yes|no" "no"
				if [ "$INPUTTEXT" == "no" ]; then
					echo "Exiting..."  | tee -a $LOG
					app_exit 1
				fi

				check_input "  Are you sure you wish to continue? (yes/no) [Default: no]" "yes|no" "no"

				if [ "$INPUTTEXT" == "no" ]; then
					echo "Exiting..."  | tee -a $LOG
					app_exit 1
				fi
				echo "WARNING: CSF detected, user accepted risk " | tee -a $LOG
			fi
		fi
	fi
}

function check_update_history() {
    if [[ $PKG == "rpm" ]]; then
        echo
        echo -n "Checking for core updates: "
        Y_LIST=$(yum list updates |wc -l)
        if [ $Y_LIST -gt 50 ]; then
            echo "Pending updates FAIL (count: $Y_LIST)" >> $LOG

            echo FAIL | tee -a $LOG
            echo  | tee -a $LOG
            echo "    A test using the yum updater on the system indicated that it is " | tee -a $LOG
			echo "    significantly out of date. ($Y_LIST updates pending)" | tee -a $LOG
            echo "    This environment may be so out of date that it will not be supportable." | tee -a $LOG
            echo | tee -a $LOG
            echo "    Recommendation: Halt the installation, and investigate the unapplied " | tee -a $LOG
			echo "    Operating System patches to the system using the command:" | tee -a $LOG
            echo "          yum list updates" | tee -a $LOG
            echo | tee -a $LOG

            if [ ! $AUTO ]; then
                    echo
                    check_input "    This environment is UNSUPPORTED. Do you wish to continue? (yes/no) [Default: no]" "yes|no" "no"
                    if [ "$INPUTTEXT" == "no" ]; then
                            echo
                            echo "Exiting..."
                            echo
                            app_exit 1
                    fi
            fi

            echo
            echo
            echo
            echo "WARNING: Pending updates, user accepted risk " >> $LOG

        else
            echo "OK"
            echo "Pending updates OK (count: $Y_LIST)" >> $LOG
        fi

    fi
}

function check_aum_plesk {
    if [ -f /etc/asl/config ]; then
        if grep -q plesk_global_default /etc/asl/config; then
            if [[ $PKG == "rpm" ]]; then
                rpm -e aum --nodeps
            elif [[ $PKG == "deb" ]]; then
                dpkg -r aum
            fi
        fi
    fi
}

function check_plesk_firewall() {
    if [ -f /etc/systemd/system/multi-user.target.wants/psa-firewall.service ]; then
        systemctl stop psa-firewall.service > /dev/null
        systemctl disable psa-firewall.service > /dev/null
    fi
}

function firewalld_disable () {
    if [ -f /etc/systemd/system/multi-user.target.wants/firewalld.service ]; then
        systemctl stop firewalld.service > /dev/null
        systemctl disable firewalld.service > /dev/null
    fi
}

function check_selinux {
        if [ -x /usr/sbin/setenforce ]; then
                /usr/sbin/setenforce 0 >/dev/null 2>&1
                if grep -q '^SELINUX=enabled$' /etc/selinux/config; then
                        /usr/bin/sed -i 's/SELINUX=.*/SELINUX=permissive/g' /etc/selinux/config
                fi
        fi
}


function check_package_conflicts() {
    COUNT=0
    CONFLICTS="MFEcma MFErt MFEhiplsm-kernel MFEhiplsm-apache cphalo cb cb-enterprise psa imunify360-venv imunify360-ossec imunify360-ossec-hybrid imunify360-ossec-server"
    
    if [ "$STANDALONE" -eq 1 ]; then
        # Remove "psa" from the list of conflicts
        CONFLICTS=$(echo "$CONFLICTS" | sed 's/psa//g')
    fi
    
    for package in $CONFLICTS; do
        if rpm -q "$package" >/dev/null; then
            ((COUNT++))
            ARRAY+=("    Incompatible package: $package ")
        fi
    done

    if [ "$COUNT" -ge 1 ]; then
        echo "    Environment incompatibility score: $COUNT"
        printf '  %s\n' "${ARRAY[@]}"
        app_exit 1
    fi
}


function check_rhel_subscriptions() {
    if [ -f /etc/redhat-release ]; then
        if grep -q "Red Hat" /etc/redhat-release; then

            # Is the system subscribed to RHN?
            if [ -x /usr/sbin/subscription-manager ]; then
                /usr/sbin/subscription-manager status | egrep -q "Overall Status: Current|host has access to content"
                if [ $? -ne 0 ]; then
                    echo "  Red Hat subscription status: Not current" | tee -a $LOG
                    echo "  Please ensure the system is subscribed to Red Hat Network" | tee -a $LOG
                    app_exit 1
                fi
            fi

            # Check if the system is running RHEL 9
            if grep -q "release 9" /etc/redhat-release; then
                # Try enabling the first repository
                dnf config-manager --enable codeready-builder-for-rhel-9-x86_64-rpms
                if [ $? -ne 0 ]; then
                    echo "  Failed to enable codeready-builder-for-rhel-9-x86_64-rpms, trying RHUI repository..." | tee -a $LOG
                    # Try enabling the second repository
                    dnf config-manager --enable codeready-builder-for-rhel-9-x86_64-rhui-rpms
                    if [ $? -ne 0 ]; then
                        echo "  Neither CodeReady Builder repository could be enabled" | tee -a $LOG
                        echo "  Please enable the appropriate CodeReady Builder repository" | tee -a $LOG
                        app_exit 1
                    fi
                fi
            fi
        fi
    fi
}


function preflight_installation {
	
	echo -n "Starting Preflight Installation Checks:" | tee -a $LOG
	echo

	#OS release check
	check_release

	#Remove asl and awp repos if they exist.
	check_prexisting_reps


	# If the system is running RHEL, check for subscriptions
	check_rhel_subscriptions

	#package conflicts
	# if PKG is rpm
	if [ $PKG == rpm ]; then
		check_package_conflicts
	fi

	if [[ ! $DEBUG ]]; then
		#Check Disk 
		if [ $STANDALONE -eq 1 ]; then
			check_diskspace /var 10 30
		else
			check_diskspace /var 40 100
		fi

		#Check Ram. 
		if  [[ $STANDALONE -eq 1 ]]; then
			check_ram  1800000
		else
			check_ram 3700000
		fi

		#Check Swap space.
		check_swap

		#Checking ports
		check_ports

		#CPU Core check
		check_cores

		#SSL check	
		check_ssl
	fi



	#CSF check
	check_csf

	#SE Linux check
	check_selinux

	# If STANDALONE then run these checks
	if [ $STANDALONE -eq 1 ]; then
	    #Check for updates
	    check_update_history

	    #Check for Plesk Firewall
	    check_plesk_firewall


	    #Check for AUM
	    check_aum_plesk
	fi

	#Check for Firewalld
	firewalld_disable
}

function post_install_standalone() {
    if [ $INSTALL_ONLY ]; then
        echo "Installation complete"
        exit 0
    fi

    AWP_CONFIG=/var/awp/etc/config
    RULES_CONFIG=/var/awp/etc/rules.json

    systemctl daemon-reload
    systemctl stop awpd

    # set username and password in file
    sed -i "s/\"USERNAME\"/\"$USERNAME\"/"  $AWP_CONFIG
    sed -i "s/\"PASSWORD\"/\"${PASSWORD}\"/"  $AWP_CONFIG
    sed -i 's/\(^OSSEC_AUTHD_DISABLED=\).*/\1\"yes\"/' $AWP_CONFIG
    sed -i 's/\(^CLUSTER_TYPE=\).*/\1\"primary\"/' $AWP_CONFIG
    sed -i 's/\(^CONFIGURED=\).*/\1\"yes\"/' $AWP_CONFIG

    echo "$(date -u) updated /var/awp/etc/config" >>$LOG
    echo "$(date -u) running /var/awp/bin/setup" >>$LOG

    echo "Initializing setup, please be patient..."
    /var/awp/bin/aum -uf -silent
    /var/awp/bin/setup
    if [ $? -ne 0 ]; then
        echo "Error: setup could not complete successfully"
        app_exit 1
    fi
    systemctl stop awpd
    /var/awp/bin/aum -uf | tee -a $LOG
    if [ $? -eq 0 ]; then
        # Enable and start services based on package type
        if [[ $PKG == "deb" ]]; then
            # Ubuntu service management
            systemctl enable ossec-hids
            systemctl start ossec-hids
            systemctl enable clamav-daemon
            systemctl enable clamav-freshclam
            systemctl start clamav-daemon
            systemctl start clamav-freshclam
        else
            # RHEL/CentOS service management
            systemctl enable ossec-hids
            systemctl start ossec-hids
            systemctl enable clamd@scan
            systemctl enable clamonacc
        fi

        echo
        echo "Starting AWPd"
        systemctl start awpd

        # Verify awpwebd is running
        echo -n "Starting AWPwebd: "
        while ! /usr/bin/pgrep awpwebd >/dev/null; do
            echo -n "."
            sleep 3
        done
        echo " Done"
        
        echo "Final setup tasks"
        n=0
        until [ $n -ge 5 ]; do
            /var/awp/bin/awp -s -f && break
            n=$(($n + 1))
            echo "Retrying in 5s..."
            sleep 5
        done
    else
        echo
        echo "ERROR: aum could not complete successfully"
        echo
        app_exit 1
    fi
}


function clear_firewall() {
    if rpm -q psa-firewall >/dev/null; then
    	if [ -f /etc/init.d/psa-firewall ]; then
            /etc/init.d/psa-firewall stop
            if [ $? -ne 0 ]; then
                echo "  Error: Plesk firewall could not be disabled"
                exit 1
            fi
    	elif [ -f /usr/lib/systemd/system/psa-firewall.service ]; then
     	   systemctl stop psa-firewall
     	   if [ $? -ne 0 ]; then
                echo "  Error: Plesk firewall could not be disabled"
                exit 1
            fi
    	fi
            rpm -e psa-firewall --nodeps >/dev/null 2>&1
    fi      
}               



#####################################
# Main
#####################################

for arg in "$@"; do
	case $arg in
		--https-proxy=*)
		HTTPS_PROXY="${arg#*=}"
		shift # Remove --https-proxy from processing
		;;
		--https-proxy-username=*)
		HTTPS_PROXY_USERNAME="${arg#*=}"
		shift # Remove --https-proxy-username from processing
		;;
		--https-proxy-password=*)
		HTTPS_PROXY_PASSWORD="${arg#*=}"
		shift # Remove --https-proxy-password from processing
		;;
		--beta)
		BETA=1
		shift # Remove --beta from processing
		;;
		# add --standalone option
		--standalone)
		STANDALONE=1
		shift # Remove --standalone from processing
		;;
		# add --install
		--install)
		INSTALL_ONLY=1
		shift # Remove --install from processing
		;;
		# add help with -h or --help
		-h|--help)
		show_help
		exit
		;;
		*)
		# unknown option
		;;
	esac
done

# if standalone, set the TITLE string to "Standalone"
if [ $STANDALONE -eq 1 ]; then
	TITLE="Atomic Workload Protection"
else
	TITLE="Atomic OSSEC Hub"
fi

#Run Preflight installation checks.

echo "`date -u` --------------------------------------------------" >> $LOG
echo "`date -u` AP installation started" >> $LOG


echo
echo
echo "${TITLE} (v$INSTALLER_VERSION)"
echo "  By Atomicorp: https://www.atomicorp.com"
echo "  Documentation: https://docs.atomicorp.com/AEO/index.html"
echo


if [ ! $SSH_TTY  ]; then
	INSTALL_TTY="/dev/$(ps -p$$ --no-heading | awk '{print $2}')"
else
	INSTALL_TTY=$SSH_TTY
fi

# If the HTTPS_PROXY environment variable is set then set the https_proxy environment variable
if [ ! -z "$HTTPS_PROXY" ]; then
	export https_proxy=$HTTPS_PROXY
fi

# If the HTTPS_PROXY_USERNAME environment variable is set then set the https_proxy_username environment variable
if [ ! -z "$HTTPS_PROXY_USERNAME" ]; then
	export https_proxy_username=$HTTPS_PROXY_USERNAME
fi 

# If the HTTPS_PROXY_PASSWORD environment variable is set then set the https_proxy_password environment variable
if [ ! -z "$HTTPS_PROXY_PASSWORD" ]; then
	export https_proxy_password=$HTTPS_PROXY_PASSWORD
fi 

preflight_installation / 3 30


# is this unattended
if [ -f awp.cfg ]; then
    source ./awp.cfg
    AUTO=1
    echo "`date -u` awp.cfg detected, running in unattended mode" >> $LOG
fi


# if not unattended, force CONFIGURED to no
if [ ! $AUTO ]; then
	CONFIGURED=no
	echo "`date -u` CONFIGURED forced to no" >> $LOG
fi

# if not unattended
if [ ! $AUTO ]; then
    # source existing v5 config if present
    if [ -f /etc/asl/config ] ; then
      	source /etc/asl/config
      	echo "`date -u` sourced /etc/asl/config" >> $LOG
		# Hub install upgrades, inherit ASL config
		cp /etc/asl/config /root/awp.cfg
		if [ ! -d /root/v5tmp ] ; then
			mkdir -p /root/v5tmp
			cp -a /etc/asl/* /root/v5tmp/
		fi

		# Check for v5 configuration_setup stuck in loop and remove it.
		echo "`date -u` Checking for v5 configuration setup..." >> $LOG
		ps -ax | grep -e "[c]onfiguration_setup.sh" | xargs |  awk '{print $1}' | xargs kill > /dev/null 2>&1
		echo "`date -u` configuration setup removal exited with code: ${?}" >> $LOG
    fi

    # source existing v6 config if present
    if [ -f /var/awp/etc/config ] ; then
        source /var/awp/etc/config
        echo "`date -u` sourced /var/awp/etc/config" >> $LOG
    fi
fi


# ask for credentials, determine TC_TARGET
if [ "$CONFIGURED" != "yes" ]; then

  echo
  echo

  # ---------  from tortix.key
  if [ -f /var/awp/etc/tortix.key ] && [ -s /var/awp/etc/tortix.key ]; then
  	if [ ! -f /usr/bin/php ]; then
		yum -y install php
  	fi
  	echo "`date -u` credentials derived from /var/awp/etc/tortix.key " >> $LOG
  	TC_TARGET="updates.atomicorp.com/channels/rules/plesk/README"
	  STEXT=`base64 -d /var/awp/etc/tortix.key`
	  USERNAME=$(php -r "\$z = unserialize('"$STEXT"'); echo \$z[\"login\"] ; ")
	  PASSWORD=$(php -r "\$z = unserialize('"$STEXT"'); echo \$z[\"pass\"] ; ")

		if [ "$USERNAME" == "" ]; then
			echo "`date -u` ERROR: username was empty (encoding error)" >> $LOG
			app_exit 1
		fi

		if [ "$PASSWORD" == "" ]; then
	        echo "`date -u` ERROR: password was empty (encoding error)" >> $LOG
			app_exit 1
		fi

		export USERNAME
		echo "`date -u` username: $USERNAME" >> $LOG
	  # ---------  from stdin
  else
    echo "`date -u` fetching credentials from stdin" >> $LOG
    TC_TARGET="updates.atomicorp.com/channels/asl-3.0/README"
		echo -n "Enter subscription Username: "
		read USERNAME < $INSTALL_TTY
		export USERNAME

		if [ "$USERNAME" == "" ]; then
		  echo "Exiting: Username is blank. "
		  echo
		  echo "`date -u` ERROR: empty username provided" >> $LOG
		  app_exit 1
		fi

		PASSCONFIRMED=0
		failed=0

		while [ $PASSCONFIRMED -lt 1 ]; do
			  if [ $failed -gt 2 ]; then
			    echo "Exiting: too many failed attempts."
			    echo
			    echo "`date -u` ERROR: too many failed attempts" >> $LOG
			    app_exit 1
			  fi

			  echo -n "Enter Subscription Password: "
			  unset PASSWORD
			  read -sr PASSWORD < $INSTALL_TTY
			  echo

		    if [ "$PASSWORD" == "" ]; then
		      echo "Exiting: Password is blank..."
		      echo "`date -u` ERROR: empty password provided" >> $LOG
		      app_exit 1
		    fi

		    unset PASSWORD2
		    echo -n "Re-Enter Subscription Password: "
			  read -sr PASSWORD2 < $INSTALL_TTY
			  echo

		    if [ "$PASSWORD" == "$PASSWORD2" ]; then
		      PASSCONFIRMED=1
		    else
		      failed=$(( $failed + 1 ))
		      echo "Sorry, passwords do not match."
		      echo
		      echo "`date -u` ERROR: password mismatch" >> $LOG
		    fi
	    done
  fi
fi

ENCPASSWORD=$(rawurlencode $PASSWORD)

echo "$(date -u) testing credentials" >>$LOG

TEST_CREDENTIALS=$(curl -s https://$USERNAME:$ENCPASSWORD@$TC_TARGET)
echo
echo -n "Verifying account: "
if [[ "$TEST_CREDENTIALS" != "Atomicorp, Inc." ]]; then
    echo "Failed"
    echo
    echo "   ERROR: AP Username/Password credentials are incorrect or this license has expired."
    echo "   For more information, please see this FAQ:"
    echo "   https://wiki.atomicorp.com/wiki/index.php/ASL_FAQ#HTTP_Error_401:_Authorization_Required_Trying_other_mirror "
    echo
    echo "$(date -u) ERROR: authorization failed" >>$LOG
    app_exit 1
else
    echo "  Passed"
    echo "$(date -u) authorization test passed" >>$LOG
fi


if [[ $PKG == "rpm" ]]; then

    echo -n "Installing the Atomic GPG key: "

    if [ !  -f /etc/pki/rpm-gpg/RPM-GPG-KEY.atomicorp.txt ]; then
        if [ ! -d /etc/pki/rpm-gpg ]; then
            mkdir -p /etc/pki/rpm-gpg/
        fi
        curl -s https://www.atomicorp.com/RPM-GPG-KEY.atomicorp.txt -o /etc/pki/rpm-gpg/RPM-GPG-KEY.atomicorp.txt
        RETVAL=$?
        if [ ! "$RETVAL" = 0 ]; then
            echo FAIL
            curl https://www.atomicorp.com/RPM-GPG-KEY.atomicorp.txt
            echo
            echo "  Could not download the Atomicorp gpg key"
            echo
            echo "`date -u` ERROR: failed to download the Atomicorp GPG key" >> $LOG
            app_exit 1
        fi
    fi
    /bin/rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY.atomicorp.txt
    echo "`date -u` Atomicorp GPG key imported" >> $LOG

    if [ ! -d /var/awp/etc ]; then
    	mkdir -p /var/awp/etc
    	echo "`date -u` created /var/awp/etc" >> $LOG
    fi



    # repo files
    #---------------------------------------------------------
    # asl6.repo
	cat  << EOF > /etc/yum.repos.d/awp.repo
[asl-6.0]
name=Atomicorp - $releasever - Atomic Web Protection 6.0
mirrorlist=file:///var/awp/etc/asl-6.0-mirrorlist
priority=1
enabled=1
gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY.atomicorp.txt

gpgcheck=1
$KERNEL

[asl-6.0-testing]
name=Atomicorp - $releasever - Atomic Web Protection 6.0 (Testing)
mirrorlist=file:///var/awp/etc/asl-6.0-testing-mirrorlist
priority=1
enabled=$BETA
gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY.atomicorp.txt
gpgcheck=1
$KERNEL
EOF


# asl.repo
	cat  << EOF > /etc/yum.repos.d/asl.repo
[asl-4.0]
name=Atomicorp - $releasever - Atomic Secured Linux 4.0
mirrorlist=file:///var/awp/etc/asl-4.0-mirrorlist
priority=1
enabled=0
gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY.atomicorp.txt

gpgcheck=1
$KERNEL

[asl-4.0-testing]
name=Atomicorp - $releasever - Atomic Secured Linux 4.0 (Testing)
mirrorlist=file:///var/awp/etc/asl-4.0-testing-mirrorlist
priority=1
enabled=0
gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY.atomicorp.txt
gpgcheck=1
$KERNEL
EOF

    #---------------------------------------------------------
    echo "`date -u` created .repo files" >> $LOG


    # mirrorlist files
    #---------------------------------------------------------
	cat << EOF > /var/awp/etc/asl-6.0-mirrorlist
https://$USERNAME:$ENCPASSWORD@updates.atomicorp.com/channels/asl-6.0/$DIR/$ARCH
EOF
	cat << EOF > /var/awp/etc/asl-6.0-testing-mirrorlist
https://$USERNAME:$ENCPASSWORD@updates.atomicorp.com/channels/asl-6.0-testing/$DIR/$ARCH
EOF
	cat << EOF > /var/awp/etc/asl-4.0-mirrorlist
https://$USERNAME:$ENCPASSWORD@updates.atomicorp.com/channels/asl-4.0/$DIR/$ARCH
EOF
	cat << EOF > /var/awp/etc/asl-4.0-testing-mirrorlist
https://$USERNAME:$ENCPASSWORD@updates.atomicorp.com/channels/asl-4.0-testing/$DIR/$ARCH
EOF

    #---------------------------------------------------------
    # HUB Installation
    #---------------------------------------------------------

	if [ $STANDALONE -eq 0 ]; then
        if [ ! -f awp.cfg ]; then

        	echo "USERNAME=\"$USERNAME\"" >> awp.cfg
        	echo "PASSWORD=\"${PASSWORD}\"" >> awp.cfg
        	echo "KERNEL_CHANNEL=\"disabled\"" >> awp.cfg
        	echo "CONFIGURED=\"yes\"" >> awp.cfg
        	echo "FW_INBOUND_TCP_SERVICES=\"22,80,443,1514,1515,1516,30001\"" >> awp.cfg
        	echo "OPENID_CONNECT_INTEGRATION=\"on\"" >> awp.cfg
        	echo "OSSEC_ACTIVE_RESPONSE=\"yes\"" >> awp.cfg
        	echo "OSSEC_NOTIFY=\"no\"" >> awp.cfg
        	echo "ALLOW_kmod_loading=\"yes\"" >> awp.cfg
        	# if HTTPS_PROXY is set, use it
        	if [ "$HTTPS_PROXY" ]; then
        		echo "HTTP_PROXY=\"$HTTPS_PROXY\"" >> awp.cfg
        	fi
        	# if HTTPS_PROXY_USERNAME, and HTTPS_PROXY_PASSWORD are set, use it
        	if [ "$HTTPS_PROXY_USERNAME" ] && [ "$HTTPS_PROXY_PASSWORD" ]; then
        		echo "HTTP_PROXY_USERNAME=\"$HTTPS_PROXY_USERNAME\"" >> awp.cfg
        		echo "HTTP_PROXY_PASSWORD=\"$HTTPS_PROXY_PASSWORD\"" >> awp.cfg
        	fi


        fi
    	source ./awp.cfg
        # Install postfix
        yum install -y postfix
        if [ $? -ne 0 ]; then
        	echo "ERROR: Unable to install postfix"
        	app_exit 1
        fi
        systemctl enable postfix || :
        systemctl start postfix || :

	fi

    # add epel release repo 
    yum install -y epel-release
    if [ $? -ne 0 ]; then
    	if [[ "$DIST" == "el9" ]]; then
    		dnf -y install https://dl.fedoraproject.org/pub/epel/epel-release-latest-9.noarch.rpm
    	elif [[ "$DIST" == "el8" ]]; then
    		dnf -y install https://dl.fedoraproject.org/pub/epel/epel-release-latest-8.noarch.rpm
    	elif [[ "$DIST" == "el7" ]]; then
    		yum -y install https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
    	else
    		echo "ERROR: Unable to install the EPEL repo (Required)"
    		echo "  if this is an internet restricted environment, switch to the Offline installation license"
    		app_exit 1
    	fi
    fi

    # EL9
    if [[ "$DIST" == "el9" ]]; then
        if ! grep -q "Red Hat" /etc/redhat-release; then
           dnf -y install dnf-plugins-core
           dnf config-manager --set-enabled crb
           # if this fails we need to exit
        if [ $? -ne 0 ]; then
            echo "ERROR: Unable to enable the CRB repo"
            app_exit 1
        fi
    fi
fi

    echo "`date -u` installing the awp package" >> $LOG
	#---------------------------------------------------------
    # Installation
    #---------------------------------------------------------
    if [[ $STANDALONE -eq 1 ]]; then
        # Pre-reqs
        clear_firewall

        echo "$(date -u) installing the awp package" >>$LOG
        PACKAGES="awp awp-web jq ${SUGGESTS}"
        yum install -y $PACKAGES | tee -a $LOG
        if [ $? -eq 0 ]; then
            if [ ! $AUTO ]; then
                cat /var/awp/data/license_agreement.txt | less -e -M -Ps"Press any key to view the next page"
                check_input "Do you agree to these terms (yes/no) [Default: yes]" "yes|no"  "yes"
                if [ $INPUTTEXT != "yes" ]; then
                    echo
                    Exiting install, License was not accepted
                fi
                echo "NOTICE: User accepted License" >> $LOG
            fi
            post_install_standalone

        else
            echo
            echo "ERROR: There was a problem with the Yum installation"
            echo "$(date -u) ERROR: base package installation failed" >>$LOG
            echo
            echo
            app_exit 1
        fi
    else
	    # Hub Install
        PACKAGES="awp awp-web httpd mod_ssl  awp-hub-utils aeo-python-utils wget rsync telnet net-tools vim-enhanced jq php yum-utils tar bind-utils ${SUGGESTS}"
        yum install -y $PACKAGES | tee -a $LOG

		if [ $INSTALL_ONLY ]; then
			echo "Installation complete"
			exit 0
		fi

        rpm -q awp
        if [ $? -eq 0 ]; then
        	if [  -f /etc/httpd/conf.d/welcome.conf ]; then
        		rm -f /etc/httpd/conf.d/welcome.conf
        	fi
        	systemctl enable httpd
        	systemctl start httpd 

        	AWP_CONFIG=/var/awp/etc/config
        	RULES_CONFIG=/var/awp/etc/rules.json

           	# reload for service files if el7
           	if [ $DIST == "el7" ] ; then
               	echo "`date -u` reloading systemctl daemon" >> $LOG
               	systemctl daemon-reload
           	fi
           	systemctl stop awpd

           	# set username and password in file
           	sed -i "s/\"USERNAME\"/\"$USERNAME\"/"  $AWP_CONFIG
           	sed -i "s/\"PASSWORD\"/\"${PASSWORD}\"/"  $AWP_CONFIG


           	echo "`date -u` updated /var/awp/etc/config" >> $LOG
           	echo "`date -u` running /var/awp/bin/setup" >> $LOG
           	echo "Initializing setup, please be patient..."


           	/var/awp/bin/setup | egrep -v "ossec-control|Restarting Ossec"
           	if [ $? -ne 0 ]; then
        		echo "Error: setup could not complete successfully"
        		exit 1
           	fi
           	systemctl stop awpd

           	# Enable services
           	jq '. +  {"syslog": [{"setting_type": "S", "rule_type": "secure", "port": "1514", "protocol": "udp", "ips_allowed": [],"ips_denied": [] }, { "setting_type": "S", "rule_type": "syslog", "port": "514", "protocol": "udp", "ips_allowed": [ "0.0.0.0/0" ], "ips_denied": [] }]}' $RULES_CONFIG > /tmp/rules.json && cp -f /tmp/rules.json $RULES_CONFIG

           	/var/awp/bin/aum -uf | tee -a $LOG
           	if [ $? -eq 0 ] ; then
        		systemctl enable ossec-hids
               	systemctl start ossec-hids
        		systemctl enable clamav-daemon

        		echo
        		echo "Starting AWP"
        		systemctl start awpd

        		# Creating installer repos
        		if [ ! -d /var/www/html/installers ]; then
        			mkdir -p /var/www/html/installers
        		fi

    			# Run mirror creation step
    			echo
    			echo "Creating agent mirror"
    			eval /etc/cron.daily/awp-mirror-update &> /dev/null &disown;
    			eval /etc/cron.daily/awp-docs-update &> /dev/null &disown;

    			# Verify awpwebd is running
    			echo -n "Starting AWPwebd: "
    			while ! /usr/bin/pgrep awpwebd >/dev/null; do
    				echo -n "."
    				sleep 3
    			done
    			echo " Done"

    			# test this next, we did that stop above it might be enough
    			echo "Final setup tasks"
    			n=0
    			until [ $n -ge 10 ]; do
    				/var/awp/bin/awp -s -f && break
    				n=$[$n+1]
    				echo "Retrying in 15s..."
    				sleep 15
    			done

    			echo "Success"


    			# Disable 332039
    			awp --rule-disable 332039
    			
    			# Compress logs
    			sed -i "s/^#compress/compress/g" /etc/logrotate.conf

    			
                # Enable EULA
            	#if [ -f /var/awp/data/.regform ]; then
            	#	rm -f /var/awp/data/.regform
            	#fi

            fi

        else
        	echo
        	echo "ERROR: There was a problem with the Yum installation"
        	echo "`date -u` ERROR: base package installation failed" >> $LOG
        	echo
        	echo
        	app_exit 1
        fi

        # Re-enable disabled repos
        if [ $ALT_REPO_DISABLED -ge 1 ]; then
        	for reponame in $ALT_REPO; do
        		/usr/bin/yum-config-manager --enable $reponame > /dev/null

        	done
        fi
    fi
elif [[ $PKG == "deb" ]]; then
    echo -n "Installing the Atomic GPG key: "
    
    if [ ! -f /etc/apt/trusted.gpg.d/atomicorp.gpg ]; then
        if [ ! -d /etc/apt/trusted.gpg.d ]; then
            mkdir -p /etc/apt/trusted.gpg.d/
        fi
        curl -s https://www.atomicorp.com/RPM-GPG-KEY.atomicorp.txt | gpg --dearmor -o /etc/apt/trusted.gpg.d/atomicorp.gpg
        RETVAL=$?
        if [ ! "$RETVAL" = 0 ]; then
            echo FAIL
            curl https://www.atomicorp.com/RPM-GPG-KEY.atomicorp.txt
            echo
            echo "  Could not download the Atomicorp gpg key"
            echo
            echo "`date -u` ERROR: failed to download the Atomicorp GPG key" >> $LOG
            app_exit 1
        fi
    fi
    echo "`date -u` Atomicorp GPG key imported" >> $LOG

    if [ ! -d /var/awp/etc ]; then
        mkdir -p /var/awp/etc
        echo "`date -u` created /var/awp/etc" >> $LOG
    fi

    # Add repository configuration
    if [[ "$DIST" != "bionic" && "$DIST" != "focal" ]]; then
        echo "ERROR: Only Ubuntu 18.04 (Bionic) and 20.04 (Focal) are supported for Ubuntu installations"
        app_exit 1
    fi

    cat << EOF > /etc/apt/sources.list.d/awp.list
deb [signed-by=/etc/apt/trusted.gpg.d/atomicorp.gpg] https://$USERNAME:$ENCPASSWORD@updates.atomicorp.com/channels/asl-6.0/ubuntu/dists/$DIST stable main
deb [signed-by=/etc/apt/trusted.gpg.d/atomicorp.gpg] https://$USERNAME:$ENCPASSWORD@updates.atomicorp.com/channels/asl-6.0-testing/ubuntu/dists/$DIST testing main
EOF

    # Update package lists
    apt-get update
    if [ $? -ne 0 ]; then
        echo "ERROR: Failed to update package lists"
        app_exit 1
    fi

    # Install required packages
    apt-get install -y awp awpwebd
    if [ $? -ne 0 ]; then
        echo "ERROR: Failed to install AWP packages"
        app_exit 1
    fi

    # Install postfix for Ubuntu
    apt-get install -y postfix
    if [ $? -ne 0 ]; then
        echo "ERROR: Unable to install postfix"
        app_exit 1
    fi

    post_install_standalone


fi

# Get the default IP address for the system
IP="$(ip route get 1 | awk '{print $7}')"
echo
echo "######################################################"
echo "${TITLE} has been installed successfully"
if [[ "$OSSEC_MODE" == "server" ]]; then
	echo "Access the AWP web console at https://$IP:30001"
fi
echo "######################################################"
echo
echo

echo "`date -u` installation complete" >> $LOG

#END