#!/bin/bash
# Copyright 2021 Atomicorp Inc.
# All rights reserved

export LANG=en_US.UTF-8
INSTALLER_VERSION=6.0.16
if [[ ! $BETA ]]; then
    BETA=0
fi

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

echo "$(date -u) --------------------------------------------------" >>$LOG
echo "$(date -u) AP installation started" >>$LOG

echo
echo
echo "##########################################################"
echo "Atomic Protector installer (v$INSTALLER_VERSION)"
echo "  By Atomicorp: https://www.atomicorp.com"
echo "  Beginning installation of the Atomic Protector platform"
echo "##########################################################"
echo

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

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


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

}

function 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 isV5Installed() {
    return $(rpm -q --quiet asl)
}

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
}


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

        SIZES=($(stat -L -f -c "%a %S" ${FILESYSTEM}))
        FREES=$((${SIZES[0]}*${SIZES[1]}))
        FREESMB=$(($FREES/1024/1024))

        echo -n "  `date -u` Freespace Check ($1): " | 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

	if [[ $PKG == "rpm" ]]; then
		ALT_REPO=$(yum -v -C repolist |awk -F: '/Repo-id/  {print $2}' |egrep -iv "^ (asl-|awp-|atomic|base|extras|updates|tortix|Appstream|Powertools|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
	fi

}

function check_ram {
	echo -n "  `date -u` MEM: "
	ram=$(free |awk '/Mem:/ {print $2}')
	swap=$(free |awk '/Swap:/ {print $2}')
	if [ $ram -lt 1800000 ]; then
		echo "FAIL - A minimuim of 2G of memory is required. Detected: $ram" | tee -a $LOG
		app_exit 1
	else
		echo "PASS"
	fi
}
function check_swap {
	echo -n "  `date -u` SWAP: "
	if [ $swap -lt 1800000 ]; then
		echo "FAIL - A minimum swap size of 2G is required for AP." | tee -a $LOG
		#app_exit 1

	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
			echo "FAIL - ${BASH_REMATCH[1]} running on 30001." | tee -a $LOG
			#app_exit 1
	else
			echo "PASS"
	fi

	#Tortixd port check
	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
			echo "FAIL - ${BASH_REMATCH[1]} running on 30000." | tee -a $LOG
			#app_exit 1
	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

	PKG=rpm
	if egrep -q "release 7" $RELEASE_FILE ; then
		DIST="el7"
		DIR=centos/7
		SUGGESTS="tortixd tortixd-mod_ssl tortix-waf tortix-mod_evasive"
	elif egrep -q "release 8" $RELEASE_FILE ; then
		DIST="el8"
		DIR=centos/8
		SUGGESTS=""
    elif egrep -q "release 9" $RELEASE_FILE ; then
        DIST="el9"
        DIR=centos/9
        SUGGEST=""
	elif egrep -q "Bionic" $RELEASE_FILE ; then
	        DIST="bionic"
        	DIR=ubuntu/18
        	PKG=deb
	elif egrep -q "Focal" $RELEASE_FILE ; then
	        DIST="focal"
        	DIR=ubuntu/20
        	PKG=deb
	else
		echo
		echo
		echo "  Error: Unable to determine distribution type. Please send the contents of $RELEASE_FILE to support@atomicorp.com" | tee -a $LOG
		echo
		echo
		app_exit 1
	fi
	echo "  `date -u` Distribution: $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 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 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 preflight_installation {

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

	#Remove asl and awp repos if they exist.
	check_prexisting_reps

	#Check Disk
	check_diskspace /var 10 30

	#Check Ram.
	check_ram

	#Check Swap space.
	check_swap

	#Checking ports
	check_ports

	#CPU Core check
	check_cores

	#SSL check
	check_ssl

	#OS release check
	check_release

	#CSF check
	check_csf

	#Updates check
	check_update_history

	#third party repo conflict check
	check_third_party

	# remove aum
	check_aum_plesk

	#If plesk, disable psa-firewall
	check_plesk_firewall

	#Disable firewalld
	firewalld_disable

	echo
	echo "Preflight Installation Checks: Complete"
	echo
}


function post_install() {
	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\"/\"$ESCAPED_PASSWORD\"/" $AWP_CONFIG
       	sed -i 's/\(^OSSEC_AUTHD_DISABLED=\).*/\1\"yes\"/' $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..."

        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
                    "  | tee -a $LOG
                    exit 1
            fi
            echo "NOTICE: User accepted License" >> $LOG
        fi

       	/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
                systemctl enable ossec-hids
                systemctl start ossec-hids
                systemctl enable clamav-daemon

                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"
                # test this next, we did that stop above it might be enough
                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

		echo
		echo "###########################################################"
		echo "                  Installation Complete                    "
        if [[ "$OSSEC_MODE" == "server" ]]; then
		    echo
            echo "Access the Atomicorp web console at https://<your_ip>:30001"
        fi
		echo "###########################################################"
		echo
		echo
	else
		echo
		echo "ERROR: aum could not complete successfully"
		echo
		app_exit 1
	fi


}

#Run Preflight installation checks.
preflight_installation / 1 10


# 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/
            touch /root/v5tmp/.update
        fi
    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

    # ---------  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

	echo
	echo "Configuring License"
        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
                echo "   Passwords do not match."
                echo
                echo "$(date -u) ERROR: password mismatch" >>$LOG
            fi
        done
    fi
fi

ENCPASSWORD=$(rawurlencode $PASSWORD)
ESCAPED_PASSWORD=$(echo $PASSWORD | sed -e 's/[\/&$]/\\&/g')

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
	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=1
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

#
if [ $BETA ]; then
cat <<EOF >/etc/yum.repos.d/asl-7.0-testing.repo
[asl-7.0-testing]
name=Atomicorp - $releasever - Atomic Protector 7.0 (Testing)
mirrorlist=file:///var/awp/etc/asl-7.0-testing-mirrorlist
priority=1
enabled=0
gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY.atomicorp.txt
gpgcheck=1
$KERNEL
EOF

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

fi

#---------------------------------------------------------
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

	#---------------------------------------------------------
	# Installation
	#---------------------------------------------------------


	# Pre-reqs
	clear_firewall

	# add epel release repo (el7 dependencies)
	yum install -y epel-release

	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
		post_install

	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

elif [[ "$PKG" == "deb" ]]; then
        /usr/bin/apt-get update
        app_error $? "apt failed to update repodata"

        /usr/bin/apt-get -y --force-yes install gpg

        curl -s  https://www.atomicorp.com/RPM-GPG-KEY.atomicorp.txt | apt-key add -
        if [ $? -ne 0 ]; then
                echo
                echo "Error: Installation failed"
                echo
                exit 1
        fi

	cat <<EOF >/etc/apt/auth.conf.d/atomicorp.conf
machine updates.atomicorp.com
  login ${USERNAME}
  password ${PASSWORD}
EOF
        chmod 600  /etc/apt/auth.conf.d/atomicorp.conf


	# Prod
        echo "deb [trusted=yes] https://updates.atomicorp.com/channels/asl-6.0/ubuntu $DIST/amd64/ " > /etc/apt/sources.list.d/awp.list

	if [ $BETA ]; then
        	echo "deb [trusted=yes] https://updates.atomicorp.com/channels/asl-6.0-testing/ubuntu $DIST/amd64/ " > /etc/apt/sources.list.d/awp-testing.list
	fi
        echo "$(date -u) updated /var/awp/etc/config" >>$LOG
        echo "$(date -u) running /var/awp/bin/setup" >>$LOG

        apt update
	app_error $? "apt update could not complete"



        apt -y install awp  awp-web  clamav-daemon clamav-freshclam clamdscan
	if [ ! -f /var/awp/bin/awp ]; then
		app_error 1 "Installation failed"
	fi
	post_install


fi

echo "$(date -u) installation complete" >>$LOG
