#!/bin/bash

INSTALL_PATH=/mnt/Install

# Configure yum
cat  << EOF > /etc/yum.repos.d/atomicorp.repo
[asl-6.0]
name=Atomicorp
baseurl=file:$INSTALL_PATH
enabled=1
gpgcheck=1
gpgkey=file:$INSTALL_PATH/RPM-GPG-KEY.atomicorp.txt
       file:$INSTALL_PATH/RPM-GPG-KEY-CentOS-Official
       file:$INSTALL_PATH/RPM-GPG-KEY-EPEL-7
EOF

# TODO: update function, so we can use this to update an installation



PACKAGES="awp awp-web httpd mod_ssl  awp-hub-utils aeo-python-utils ansible wget wireshark rsync nmap telnet net-tools vim-enhanced jq php yum-utils tar ossec-hids-server"

yum -y install  $PACKAGES
if [ $? -ne 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
        systemctl daemon-reload


	systemctl stop awpd

	/var/awp/bin/setup
	systemctl stop awpd

	# manual rules copy
	pushd /var/awp/data/rules/
		tar xvf $INSTALL_PATH/rules/clamav-*.tar.bz2
		tar xvf $INSTALL_PATH/rules/geomap-*.tar.bz2
		tar xvf $INSTALL_PATH/rules/modsec-*.tar.bz2
		tar xvf $INSTALL_PATH/rules/ossec-*.tar.bz2
	popd
	
        echo
        echo "Starting AWP"
        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
        awp --rule-disable 332039


        systemctl enable ossec-hids
        systemctl enable clamav-daemon
	systemctl start ossec-hids
	systemctl start clamav-daemon	

	# Build repos
	pushd /var/www/html/channels/
		tar xvf $INSTALL_PATH/awp-hub-repo.tar.gz
	popd

	# TODO create user

        echo "Access the AWP web console at https://<your_ip>:30001"

fi


