#!/bin/bash
# OSSEC Agent installer
# Name: ossec-installer.sh
# Copyright Atomicorp 2024
# License: Commercial. Unauthorized redistribution prohibited.

###################
# Global variables
###################

ROOT_UID=0
USE_AWS=0
VERSION=8.1
AWS_IP="169.254.169.254"
O_CONF="/var/ossec/etc/ossec.conf"
LOG=/var/log/atomicorp.log
HTTP="http"



###################
# Functions
###################

function show_help() {

	echo
	echo "Atomicorp OSSEC Agent installer ($VERSION)"
	echo "Usage: $0 <server_ip>"
	echo "  example: $0 10.11.12.13"
	echo "  or"
	echo "  example: $0 --server 10.11.12.13"

	echo
	echo
	echo "options (deprecated):"
	echo "	<server_ip>	          IP of server hub"
	echo "	<auth_ip>	optional. IP of registration service. Default: <server_ip>"
	echo "	<protocol>	optional. Protocol tcp or udp"
	echo "	<port>		optional. Port for remoted"
	echo "	<group>		optional. Group to assign agent"
	echo
	echo "command line parameters:"
	echo "	--server <server_ip>       IP/Hostname of the server hub"
	echo "	--auth <auth_ip>           IP/Hostname of the registration service. Default: <server_ip>"
	echo "	--password <password>      Registration authentication password"
	echo "	--port <port>              Port for remoted"
	echo "	--protocol <tcp|udp>       Protocol for remoted"
	echo
	echo "	--agent-name <name>        Set agent name [Default: hostname]"
	echo "	--default-name             Prepend the external IP of the agent to agent name"
	echo "	--group  <groupname>       Group to assign agent"
	echo "	--https                    Use https for installation"
	echo "	--install-only             Only install the agent, do not register"
	echo "	--proxy <disable|url>      Proxy settings. Proxy URL, or disable proxy for this installation"
	echo "	--use-aws                  Use the AWS instance ID for the agent name"
	echo "	--version                  Show Version"
	echo
	echo "environment variables"
	echo "	example: export SERVER_IP=10.11.12.13 $0"
	echo
	echo "	AUTH_IP  	IP of server registration service. "
	echo "	GROUP	  	Group to assign agent"
	echo "	PASSWORD  	Registration authentication password"
	echo "	PROTOCOL  	Protocol tcp or udp"
	echo "	PORT	  	Port for remoted"
	echo "	SERVER_IP  	IP of server hub"
	echo

}

# log and messaging facility
# If type is set to log, and DEBUG is true, then the message will be echoed to the console
# if type is log, only write to the log file
# if type is debug, only write to the console
show_msg() {
	msg=$1

	if [[ $2 == "log" ]]; then
		if [[ $DEBUG ]]; then
			echo "$(date) DEBUG: $msg"
		fi
		echo "$(date) $msg" >> $LOG
	elif [[ $2 == "error" ]]; then
		echo $msg
		echo "$(date) $msg" >> $LOG
	elif [[ $2 == "debug" ]]; then
		echo "$(date) DEBUG: $msg"
		echo "$(date) DEBUG: $msg" >> $LOG
	else 
		echo $msg
	fi
}

function detect_downloader() {
    if [ -f /bin/curl ]; then
        GET="/bin/curl -s -O"
    elif [ -f /usr/bin/curl ]; then
        GET="/usr/bin/curl -s -O"
    elif [ -f /usr/local/bin/curl ]; then
        GET="/usr/local/bin/curl -s -O"
    elif [ -f /bin/wget ]; then
        GET="/bin/wget -q"
    elif [ -f /usr/bin/wget ]; then
        GET="/usr/bin/wget -q"
    elif [ -f /opt/freeware/bin/curl ]; then
        GET="/opt/freeware/bin/curl -s -O"
    elif [ -f /opt/freeware/bin/wget ]; then
        GET="/opt/freeware/bin/wget -q"
    else
	show_msg "ERROR: downloader not detected. Exiting" error
        exit 1
    fi
	show_msg "GET=$GET" log
}

# Smoketests
function smoketest() {
   	$GET ${HTTP}://${SERVER_IP}/tests/diag.sh | tee -a $LOG
	mv diag.sh /var/ossec/bin/
	chmod +x /var/ossec/bin/diag.sh
	/var/ossec/bin/diag.sh agent| tee -a $LOG
}

function password_auth() {
	if [ -n "$PASSWORD" ]; then
		echo "$PASSWORD" > /var/ossec/etc/authd.pass
		chmod 640 /var/ossec/etc/authd.pass
		chown root.ossec /var/ossec/etc/authd.pass
		show_msg "Password added to /var/ossec/etc/authd.pass" log
	fi
}



app_error() {
	RETVAL=$1
	MSG=$2
    if [ $RETVAL -ne 0 ];then
		echo
		show_msg "  ERROR: $MSG ($RETVAL)" error
		echo
		exit 1
   	fi
}

app_error_authd() {
	RETVAL=$1
	MSG=$2
	if [ $RETVAL -ne 0 ];then
		echo
		show_msg "  ERROR: $MSG ($RETVAL)" error
		echo
		show_msg "###############################################" error
		show_msg "Running Diagnostics: " error
		show_msg "###############################################" error
		show_msg
		show_msg "  Testing agent-auth validity: " error
		/var/ossec/bin/agent-auth -h | tee -a $LOG
		if [ $? -eq 0 ]; then
			echo
			show_msg "  Testing agent-auth connectivity: " error
			/var/ossec/bin/agent-auth -m ${AUTH_IP} | tee -a $LOG
			echo
		fi
		echo

		if [ -f /usr/sbin/getenforce ]; then
			echo -n "  Getting SELinux state: "  | tee -a $LOG
			getenforce | tee -a $LOG
		fi
		if [ -f /usr/bin/audit2allow ] ; then
			echo
			echo -n "  Running audit2allow please be patient: "	| tee -a $LOG
			audit2allow -a > /root/audit2allow-ossec.log
			echo "done"| tee -a $LOG
			echo
			cat /root/audit2allow-ossec.log| tee -a $LOG
		fi
		echo

		exit 1
		
	fi
}

aws_register () {
  echo ""
  echo "inside aws_register function."
  echo
  #this is held over from the previous version. IF this command works then it finishes method one. OTherwise, attempt method 2.
  echo "Attempting to determine instance id using IMDSv1 method..."
  curl -fs ${HTTP}://$AWS_IP/latest/meta-data/instance-id
  ret=$?
  if [ "$ret" -ne 0 ]; then
		echo
		#method 2 needs a token to my knowledge, so it gets one and does this curl.
		show_msg " ERROR: Could not determine instance-id using IMDSv1 method. Attempting IMDSv2 method..." error
		TOKEN=curl -fs http://169.254.169.254/latest/api/token -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"
		instance_id=$(curl -fs http://169.254.169.254/latest/meta-data/instance-id -H "X-aws-ec2-metadata-token: $TOKEN")
		ret=$?
		#if method 2 fails, just exit.
		if [ "$ret" -ne 0 ]; then 
			echo 
			show_msg " ERROR: Could not determine instance-id using IMDSv2 method. Exiting..." error
			exit 1
		else 
			#method 2 success block, similar to method 1.
			echo
			echo "Success, authenticating..."
			echo
			#register agent
			/var/ossec/bin/agent-auth -m ${AUTH_IP} -A ${instance_id} -G ${GROUP} | tee -a $LOG
      		app_error_authd ${PIPESTATUS[0]} "  aws_register: agent authorization failed"
  	   		show_msg "AGENT_NAME=$instance_id" log
		fi
  else 
		#method 1 success block
		echo
		echo "Success, authenticating..."
		echo
		#Obtain Agent Name
		AGENT_NAME=$(curl -fs ${HTTP}://$AWS_IP/latest/meta-data/instance-id)

		#Register the Agent
       /var/ossec/bin/agent-auth -m ${AUTH_IP} -A ${AGENT_NAME} -G ${GROUP} | tee -a $LOG
       app_error_authd ${PIPESTATUS[0]} "  aws_register: agent authorization failed"
  	   show_msg "AGENT_NAME=$AGENT_NAME" log
  fi
}


ossec_conf_update(){
	MSG="configuration failed for Hub server destination"
	# Test for ossec.conf server-ip
	if ! grep -q ${SERVER_IP} $O_CONF; then
	    if grep -q address $O_CONF; then
		    sed -i "s/<address>.*/<address>${SERVER_IP}<\/address>\n      <port>${PORT}<\/port>/g" $O_CONF
		    app_error ${PIPESTATUS[0]} $MSG
		    sed -i "s/<protocol>.*/<protocol>${PROTOCOL}<\/protocol>/g" $O_CONF
		    app_error ${PIPESTATUS[0]} $MSG
		    sed -i "s/<manager_address>.*/<manager_address>${AUTH_IP}<\/manager_address>/g" $O_CONF
		    app_error ${PIPESTATUS[0]} $MSG
	    # Legacy
	    elif grep -q server-ip $O_CONF; then
		    sed -i "s/<server-ip>.*/<server><address>${SERVER_IP}<\/address><port>${PORT}<\/port><protocol>${PROTOCOL}<\/protocol><\/server>/g" $O_CONF
		    app_error ${PIPESTATUS[0]} $MSG
	    fi
	fi

	# if the AGENT_NAME is set, then update the agent_name value in the config or add it if it doesn't exist
	if [ -n "$AGENT_NAME" ]; then
		if grep -q "<agent_name>" $O_CONF; then
			sed -i "s/<agent_name>.*/<agent_name>${AGENT_NAME}<\/agent_name>/g" $O_CONF
			app_error ${PIPESTATUS[0]} "  ossec_conf_update: agent_name update failed"
		else
			# Look for the <enrollment> line and add <agent_name> after it
			sed -i "/<enrollment>/a      <agent_name>${AGENT_NAME}<\/agent_name>" $O_CONF 
			sed -i "/<agent_name>/s/^/      /" $O_CONF
			app_error ${PIPESTATUS[0]} "  ossec_conf_update: agent_name add failed"
		fi
	else
		sed -i "/<agent_name>/d" "$O_CONF"
		app_error ${PIPESTATUS[0]} "  ossec_conf_update: groups remove failed"
	fi

	if [ -n "$GROUP" ]; then
		if grep -q "<groups>" $O_CONF; then
			sed -i "s/<groups>.*/<groups>${GROUP}<\/groups>/g" $O_CONF
			app_error ${PIPESTATUS[0]} "  ossec_conf_update: groups update failed"
		else
	        sed -i "/<enrollment>/a      <groups>${GROUP}<\/groups>" "$O_CONF" 
			sed -i "/<groups>/s/^/      /" "$O_CONF"
			app_error ${PIPESTATUS[0]} "  ossec_conf_update: groups add failed"
		fi
	else
		sed -i "/<groups>/d" "$O_CONF"
		app_error ${PIPESTATUS[0]} "  ossec_conf_update: groups remove failed"
	fi


 
	

}

key_generate() {
	if [[ $NO_REGISTER -eq 1 ]]; then
		show_msg "Agent registration skipped" log
	else
		# Add agent key
		if [ ! -f /var/ossec/etc/client.keys ]; then
			if [ "$USE_AWS" -eq 1 ]; then
				aws_register
			else
				if [ -z "$AGENT_NAME" ]; then
					/var/ossec/bin/agent-auth -m ${AUTH_IP} -G ${GROUP} -I any |tee -a $LOG
					app_error_authd ${PIPESTATUS[0]} "  key_generate: agent authorization failed"
				else
					/var/ossec/bin/agent-auth -m ${AUTH_IP} -A ${AGENT_NAME} -G ${GROUP} -I any |tee -a $LOG
					app_error_authd ${PIPESTATUS[0]} "  key_generate[named agent]: agent authorization failed"
				fi
			fi
		fi

		chown ossec.ossec /var/ossec/etc/client.keys
		chmod 640 /var/ossec/etc/client.keys
		chown root.ossec /var/ossec/etc
		chmod 770 /var/ossec/etc
	fi
}

yum_install () {
	# check for repo
	cat  << EOF > /etc/yum.repos.d/atomicorp-ossec.repo
[atomicorp-ossec]
baseurl = ${HTTP}://${SERVER_IP}/channels/awp-hub-repo/${DIR}/\$basearch
gpgcheck = 1
gpgkey = ${HTTP}://${SERVER_IP}/RPM-GPG-KEY.atomicorp.txt
name = Atomicorp Workload Protection
sslverify = 0
EOF

	# Test for selinux policy
	# Remove the SELinux policy, this handles the condition if /var/ossec was rm -rf'd
	if [ ! -d /var/ossec ]; then
		if command -v getenforce > /dev/null 2>&1 && command -v semodule > /dev/null 2>&1; then
		  if [ $(getenforce) != "Disabled" ]; then
		    if (semodule -l | grep ossec_agent > /dev/null); then
		      semodule -X 200 -r ossec_agent > /dev/null || :
		    fi
		  fi
		fi
	fi


	# Test for agent install
	if ! rpm -q ossec-hids-agent >/dev/null; then
	    	yum -y install ossec-hids-agent | tee -a $LOG
	    	app_error ${PIPESTATUS[0]} "yum failed during installation"
	else
	    	show_msg "OSSEC Agent install detected"
	fi

	if [  ! -d /var/ossec/ ]; then
	    	echo
	    	show_msg "  ERROR: /var/ossec not detected. Client installation failure?"
	    	echo "  exiting..."
		echo
	    	exit 1
	fi

	ossec_conf_update
	key_generate

	if [[ $NO_REGISTER -eq 1 ]]; then
    		show_msg "Installation only: skipping start"
	else
		show_msg "Restarting OSSEC Agent"
		echo
		/var/ossec/bin/ossec-control restart
	fi
}

zypper_install () {

        # Add keys
        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
                $GET ${HTTP}://${SERVER_IP}/RPM-GPG-KEY.atomicorp.txt >> $LOG 2>&1
                rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY.atomicorp.txt
        fi

        # Add repo
	zypper ar ${HTTP}://${SERVER_IP}/channels/awp-hub-repo/opensuse/15.1/x86_64/ atomic-ossec


        # Install package
        /usr/bin/zypper --gpg-auto-import-keys -n install ossec-hids-agent

	ossec_conf_update
	key_generate

	if [[ $NO_REGISTER -eq 1 ]]; then
    		show_msg "Installation only: skipping start"
	else
		# Start service
		service ossec-hids status >/dev/null 2>&1
		if [ $? -ne 0 ]; then
			/var/ossec/bin/ossec-control restart
		fi
	fi


}


apt_install () {


	if [ ! -f /usr/bin/gpg ]; then
	  	apt -y update | tee -a $LOG
		app_error ${PIPESTATUS[0]} "apt failed to update repodata"
	  	apt -y install gpg | tee -a $LOG
		app_error ${PIPESTATUS[0]} "apt failed to install gpg"
  	fi

  	if [ ! -f RPM-GPG-KEY.atomicorp.txt ]; then
    		$GET ${HTTP}://${SERVER_IP}/RPM-GPG-KEY.atomicorp.txt
		if [ $? -ne 0 ]; then
			$GET https://www.atomicorp.com/RPM-GPG-KEY.atomicorp.txt | tee -a $LOG
		fi
  	fi


    	if [ -d /etc/apt/trusted.gpg.d ]; then
		if [ ! -f /etc/apt/trusted.gpg.d/atomic.gpg ]; then
        		gpg --dearmor RPM-GPG-KEY.atomicorp.txt
        		app_error ${PIPESTATUS[0]} "could not dearmor GPG key, Exiting...."
			mv RPM-GPG-KEY.atomicorp.txt.gpg /etc/apt/trusted.gpg.d/atomic.gpg
			chmod 644 /etc/apt/trusted.gpg.d/atomic.gpg
        		app_error ${PIPESTATUS[0]} "could not install GPG key, Exiting...."
		fi
	else
		# Legacy system
		cat RPM-GPG-KEY.atomicorp.txt | apt-key add -
		app_error ${PIPESTATUS[0]} "could not install GPG key (Legacy), Exiting...."
    	fi



  	if [ -d /etc/apt/sources.list.d/ ]; then
   		APT_SOURCES="/etc/apt/sources.list.d/atomicorp-ossec.list"
   		echo -n "Adding [atomicorp-ossec] to $APT_SOURCES: " | tee -a $LOG
   		echo "deb ${HTTP}://${SERVER_IP}/channels/awp-hub-repo/$DIST $DIR/$ARCH/" > $APT_SOURCES
   		echo "deb [arch=${ARCH} signed-by=/etc/apt/trusted.gpg.d/atomic.gpg] ${HTTP}://${SERVER_IP}/channels/awp-hub-repo/${DIST} ${DIR} main" > $APT_SOURCES
   		echo "OK" | tee -a $LOG
  	else
   		APT_SOURCES="/etc/apt/sources.list"
   		echo -n "Adding [atomicorp-ossec] to $APT_SOURCES: " | tee -a $LOG
   		echo "deb [arch=${ARCH} signed-by=/etc/apt/trusted.gpg.d/atomic.gpg ]] ${HTTP}://${SERVER_IP}/channels/awp-hub-repo/${DIST} ${DIR} main" >> /etc/apt/sources.list
   		echo "OK" | tee -a $LOG
  	fi


  	echo
  	show_msg "Updating system ... "
  	apt -y update | tee -a $LOG

  	if ! apt list --installed | grep -q ossec-hids-agent ; then
   		DEBIAN_FRONTEND=noninteractive  apt install -o  Dpkg::Options::="--force-confmiss" -y ossec-hids-agent | tee -a $LOG
		app_error ${PIPESTATUS[0]} "Apt failed during installation."
  	else
   		show_msg "OSSEC Agent already installed."
  	fi

  	if [ ! -d /var/ossec/ ]; then
		echo
		show_msg "ERROR: /var/ossec not detected. Agent installation failure?"
  	fi

	ossec_conf_update
	key_generate

	if [[ $NO_REGISTER -eq 1 ]]; then
    		show_msg "Installation only: skipping start"
	else
		service ossec-hids restart >/dev/null 2>&1
		if [ $? -ne 0 ]; then
		    if [ -f /var/ossec/bin/ossec-control ]; then
				show_msg "Restarting OSSEC Agent"
				echo
				/var/ossec/bin/ossec-control restart > /dev/null 2>&1
			else
				service ossec start
		    fi
		fi
	fi

}

function proxy_config() {
	if [[ $PROXY == "disable" ]]; then
		show_msg "  Proxy disabled" 
		unset http_proxy
		unset https_proxy
		if [[ "$PKG" = "deb" ]]; then
			show_msg "Bypassing proxy settings from apt in /etc/apt/apt.conf.d/atomcorp-proxy.conf" debug
 			echo "Acquire::http::Proxy {" > /etc/apt/apt.conf.d/atomcorp-proxy.conf
    		echo "   $SERVER_IP DIRECT;" >> /etc/apt/apt.conf.d/atomcorp-proxy.conf
    		echo "};" >> /etc/apt/apt.conf.d/atomcorp-proxy.conf
		elif [[ "$PKG" = "rpm" ]]; then
			show_msg "Removing proxy settings from /etc/yum.conf or /etc/dnf/dnf.conf" debug
			sed -i "/^proxy/d" "$(readlink -f /etc/yum.conf)"
		fi
	elif [[ $PROXY ]]; then
		# verify that $PROXY is a valid URL
		URL_PATTERN="^(http|https|ftp)://(([^:/?#]+)(:([^/?#]*))?@)?([^/?#]+)(/[^?#]*)?(\?([^#]*))?(#(.*))?$"
		if [[ $PROXY =~ $URL_PATTERN ]]; then
			show_msg "  Proxy URL: $PROXY " 
			if [[ "$PKG" = "deb" ]]; then
				echo "Acquire::http::Proxy {" > /etc/apt/apt.conf.d/atomcorp-proxy.conf
				echo "   $PROXY;" >> /etc/apt/apt.conf.d/atomcorp-proxy.conf
				echo "};" >> /etc/apt/apt.conf.d/atomcorp-proxy.conf
			elif [[ "$PKG" = "rpm" ]]; then
				if ! grep -q "proxy.*$PROXY" /etc/yum.conf; then
					echo "proxy=$PROXY" >> "$(readlink -f /etc/yum.conf)"
				fi
			fi
		else
			show_msg "Proxy URL is invalid" 
			show_msg "Exiting" log
			exit 1
		fi
	fi
}

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

if [[ $1 == -* ]]; then
    while [ $# -gt 0 ]; do
    		case "$1" in
    				--server)
    						shift
    						SERVER_IP=$1
    						;;
    				--authserver)
    						shift
    						AUTH_IP=$1
    						;;
    				--password)
    						shift
    						PASSWORD=$1
    						;;
    				--protocol)
    						shift
    						PROTOCOL=$1
    						;;
    				--port)
    						shift
    						PORT=$1
    						;;
    				--proxy)
    						shift
    						PROXY=$1
    						;;
    				--agent-name)
    						shift
    						AGENT_NAME=$1
    						;;
    				--group)
    						shift
    						GROUP=$1
    						;;
    				--debug|-d)
    						shift
    						DEBUG=1
							;;
    				--https)
    						shift
    						HTTP="https"
							show_msg "called --use-https" log
							;;
    				--version|-v)
    						echo "Atomic OSSEC Installer Version: ${VERSION}"
    						exit
    						;;
    				--help|-h)
    						show_help
    						exit 0
    						;;
    		esac
    		shift
    done
fi

# Legacy method
if [ ! ${SERVER_IP} ]; then
	echo "WARNING: Deprecated mode detected"
    SERVER_IP=$1
fi

if [ ! ${AUTH_IP} ]; then
    if [[ "$2" != *--* ]]; then
        AUTH_IP=$2
    fi
fi

if [ ! ${PROTOCOL} ]; then
        if [[ "$3" != *--* ]]; then
                PROTOCOL=$3
        fi
fi
if [ ! ${PORT} ]; then
        if [[ "$4" != *--* ]]; then
                PORT=$4
        fi
        if [ ! ${PORT} ]; then
                PORT=1514
        fi
fi

if [ ! ${GROUP} ]; then
        if [[ "$5" != *--* ]]; then
		GROUP=$5
	fi
fi


if [ ! ${SERVER_IP} ]; then
	show_help
	exit 1
fi

# Set defaults
if [ ! ${AUTH_IP} ]; then
	AUTH_IP=$SERVER_IP
fi

if [ ! ${PROTOCOL} ]; then
	PROTOCOL=udp
fi

if [ ! ${GROUP} ]; then
	GROUP=default
fi

if [ ! "$UID" ]; then
	UID=$(id -u)
fi

if [ "$UID" -ne "$ROOT_UID" ] ; then
	echo
	echo "  ERROR: You must be root to run this program."
	echo "  exiting..."
	echo
	exit 1
fi

echo
show_msg "Atomicorp OSSEC Agent installer ($VERSION)" 
show_msg "SERVER_IP=${SERVER_IP} AUTH_IP=${AUTH_IP} PROTOCOL=${PROTOCOL} GROUP=${GROUP}" log

if [[ $* == *--default-name* ]]; then
	#install dig
	externIP="$(dig +short myip.opendns.com @resolver1.opendns.com)"
	hostname="$(hostname)"
	AGENT_NAME=$externIP"-"$hostname
	show_msg "called --default-name" log
	show_msg "externIP=${externIP} hostname=${hostname} AGENT_NAME=${AGENT_NAME}" log
fi

if [[ $* == *--install-only ]]; then
	NO_REGISTER=1	
	show_msg "called --install-only" log
fi

if [[ $* == *--use-aws ]]; then
	USE_AWS=1
	show_msg "called --use-aws" log
fi



# Detect release/package type
PKG=rpm
if [ -f /etc/redhat-release ]; then
        RELEASE=/etc/redhat-release
elif [ -f /etc/os-release ]; then
        RELEASE=/etc/os-release
elif [ -f /etc/openvz-release ]; then
        RELEASE=/etc/openvz-release
elif [ -f /etc/SuSE-release ]; then
        RELEASE=/etc/SuSE-release
elif [ -f /etc/os-release ]; then
        RELEASE=/etc/os-release
elif [ -f /etc/lsb-release ]; then
        RELEASE=/etc/lsb-release
elif [ -f /etc/debian_version ]; then
        RELEASE=/etc/debian_version
elif [ -f /etc/openvz-release ]; then
        RELEASE=/etc/openvz-release
elif [ -f /etc/virtuozzo-release ]; then
        RELEASE=/etc/virtuozzo-release
elif [[ $OSTYPE == "aix"* ]]; then
	PKG=aix
else
    echo "Error: unable to identify operating system"
    exit 1
fi

if [[ $OSTYPE == "aix"* ]]; then
	PKG=aix
elif egrep -q "(release 5)" $RELEASE ; then
	DIST="el5"
	DIR=centos/5
elif egrep -q "(release 6|release 2012)" $RELEASE ; then
	DIST="el6"
	DIR=centos/6
elif egrep -q "(release 7|release 2014)" $RELEASE ; then
	DIST="el7"
	DIR=centos/7
elif egrep -q "(release 8)" $RELEASE ; then
	DIST="el8"
	DIR=centos/8
elif egrep -q "(release 9)" $RELEASE ; then
    DIST="el9"
    DIR=centos/9
elif egrep -q "Red Hat Enterprise Linux.* 7" $RELEASE ; then
	DIST="el7"
	DIR=redhat/7
elif egrep -q "Red Hat Enterprise Linux.* 8" $RELEASE ; then
	DIST="el8"
	DIR=redhat/8
elif egrep -q "(Amazon Linux 2)" $RELEASE; then
	DIST="amazon"
	DIR=amazon/2
elif egrep -q "(Amazon Linux AMI|Amazon)" $RELEASE ; then
	DIST="el6"
	DIR=centos/6
elif egrep -q "wheezy" $RELEASE ; then
	DIST="debian"
	DIR="wheezy"
	PKG=deb
	ARCH=$(dpkg --print-architecture)
elif egrep -q "jessie" $RELEASE ; then
	DIST="debian"
	DIR="jessie"
	PKG=deb
	ARCH=$(dpkg --print-architecture)
elif egrep -q "stretch" $RELEASE ; then
	DIST="debian"
	DIR="stretch"
	PKG=deb
	ARCH=$(dpkg --print-architecture)
elif egrep -q "lucid" $RELEASE ; then
	DIST="debian"
	DIR="lucid"
	PKG=deb
	ARCH=$(dpkg --print-architecture)
elif egrep -q "precise" $RELEASE ; then
	DIST="debian"
	DIR="precise"
	PKG=deb
	ARCH=$(dpkg --print-architecture)
elif egrep -q "Raring Ringtail" $RELEASE ; then
	DIST="debian"
	DIR="raring"
	PKG=deb
	ARCH=$(dpkg --print-architecture)
elif egrep -q "Trusty Tahr" $RELEASE ; then
	DIST="ubuntu"
	DIR="trusty"
	PKG=deb
	ARCH=$(dpkg --print-architecture)
elif egrep -q "Xenial" $RELEASE ; then
	DIST="ubuntu"
	DIR="xenial"
	PKG=deb
	ARCH=$(dpkg --print-architecture)
elif egrep -q "Bionic" $RELEASE ; then
	DIST="ubuntu"
	DIR="bionic"
	PKG=deb
	ARCH=$(dpkg --print-architecture)
elif egrep -q "Focal Fossa" $RELEASE; then 
	DIST="ubuntu"
	DIR="focal"
	PKG=deb
	ARCH=$(dpkg --print-architecture)
elif egrep -q "Jammy Jellyfish" $RELEASE; then 
	DIST="ubuntu"
	DIR="jammy"
	PKG=deb
	ARCH=$(dpkg --print-architecture)
elif egrep -q "Noble Numbat" $RELEASE; then 
	DIST="ubuntu"
	DIR="noble"
	PKG=deb
	ARCH=$(dpkg --print-architecture)
elif egrep -q "buster" $RELEASE ; then
	DIST="debian"
	DIR="buster"
	PKG=deb
	ARCH=$(dpkg --print-architecture)
elif egrep -q "bullseye" $RELEASE ; then
	DIST="debian"
	DIR="bullseye"
	PKG=deb
	ARCH=$(dpkg --print-architecture)
elif egrep -q "bookworm" $RELEASE ; then
	DIST="debian"
	DIR="bookworm"
	PKG=deb
	ARCH=$(dpkg --print-architecture)
elif egrep -q "openSUSE Leap" $RELEASE; then
	DIST="suse15"
	DIR="opensuse/15.1"
	PKG=zypper
else
	echo "Error: Unable to determine distribution type. Please send the contents of $RELEASE to support@atomicorp.com"
	exit 1
fi

show_msg "RELEASE=$RELEASE DIST=$DIST DIR=$DIR PKG=$PKG ARCH=$ARCH" log

echo
proxy_config
detect_downloader
password_auth

if [ "$PKG" == "rpm" ]; then
    yum_install
	if [[ $NO_REGISTER -eq 1 ]]; then
  		show_msg "Installation only: skipping smoketest"
	else
		smoketest
	fi
elif [ "$PKG" == "deb" ]; then
    apt_install
    if [[ $NO_REGISTER -eq 1 ]]; then
        show_msg "Installation only: skipping smoketest"
    else
        smoketest
    fi
elif [ "$PKG" == "zypper" ]; then
	zypper_install
    if [[ $NO_REGISTER -eq 1 ]]; then
        show_msg "Installation only: skipping smoketest"
    else
        smoketest
    fi

elif [[ $PKG == "aix" ]]; then
  # Is RPM available
  if ! which rpm >/dev/null; then
    echo
    echo "Error: RPM not found. Exiting.... "
    exit 1
  fi

  # Is yum available
  if ! which yum >/dev/null; then
    echo
    echo "Error: Yum not found. Exiting.... "
    exit 1
  fi

  # Check for repo, and add
  if [ ! -d /opt/freeware/etc/yum.repos.d/ ]; then
    echo "Error: Yum repos.d could not be found. Exiting.... "
    exit 1
  fi

  REPOPATH=/opt/freeware/etc/yum.repos.d/


  if [ ! -f  ${REPOPATH}/atomicorp-ossec.repo ]; then
  	cat  << EOF > ${REPOPATH}/atomicorp-ossec.repo
[atomicorp-ossec]
baseurl = ${HTTP}://${SERVER_IP}/channels/awp-hub-repo/aix/7/ppc/
gpgcheck = 0
gpgkey = ${HTTP}://${SERVER_IP}/RPM-GPG-KEY.atomicorp.txt
name = Atomicorp OSSEC HIDS repo
sslverify = 0
EOF
  fi

  # Test for agent install
  if ! rpm -q ossec-hids-agent >/dev/null; then
    yum -y install ossec-hids-agent
    if [ $? -ne 0 ];then
      echo "ERROR: yum failed during installation"
      exit 1
    fi
  else
      echo
      echo "OSSEC Agent install detected"
      echo
  fi
  if [  ! -d /var/ossec/ ]; then
      echo
      echo "  ERROR: /var/ossec not detected. Client installation failure?"
      echo "  exiting..."
      echo
      exit 1
  fi


  # register with server
  if [ !  -f /var/ossec/etc/client.keys ]; then
    /var/ossec/bin/agent-auth  -m ${AUTH_IP} -G ${GROUP}
    if [ $? -ne 0 ]; then
      echo
      echo "  ERROR: agent-auth failed during registration"
      echo "  exiting..."
      exit 1
    fi
  fi

  # Update config
  if [ ! /opt/freeware/bin/sed ]; then
  	yum -y install sed
  fi
  O_CONF="/var/ossec/etc/ossec-agent.conf"
  export PATH=/opt/freeware/bin:$PATH
  ossec_conf_update

  # start service
  show_msg "Restarting OSSEC Agent"
  echo
  /var/ossec/bin/ossec-control restart

  # Add to startup
fi

show_msg "Installation Complete  . . . "
echo
