#!/bin/sh
# Copyright Atomicorp, Inc
# 2020

INSTALLER_VERSION=6.0.7
if [[ ! $BETA ]]; then
	BETA=0
fi


LOG=/root/awp-install.log
ARCH=$(uname -i)
ALT_REPO_DISABLED=0

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


echo
echo
echo "Atomic Workload Protection Hub installer (v$INSTALLER_VERSION)"
echo "  By Atomicorp: https://www.atomicorp.com"
echo "  Beginning unattended installation of the AWP Hub platform"
echo


if [ ! $SSH_TTY  ]; then
	INSTALL_TTY="/dev/$(ps -p$$ --no-heading | awk '{print $2}')"
else
	INSTALL_TTY=$SSH_TTY
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 "`date -u` ERROR: abnormal exit $EXIT_CODE" >> $LOG
    exit $EXIT_CODE
}

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 v5Backup {
	# backup existing v5 config
	if [ -f /etc/asl/config ] ; then
		mv /etc/asl/config /etc/asl/config.preupgrade
		echo "`date -u` /etc/asl/config moved to /etc/asl/config.preupgrade" >> $LOG
	fi

	# backup /etc/asl to /etc/asl.backup
	if rpm -q --quiet asl; then
		mv /etc/asl /etc/asl.backup
	fi

}



# Main

# 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
    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
    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=$($GET -nv https://$USERNAME:$ENCPASSWORD@$TC_TARGET -O - 2>&1)
echo -n "Verifying account: "
if [ "$TEST_CREDENTIALS" == "Authorization failed." ]; then
  echo " Failed"
  echo
  echo "   ERROR: AWP 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

# get os release file
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/openvz-release ]; then
	RELEASE_FILE=/etc/openvz-release
elif [ -f /etc/virtuozzo-release ]; then
	RELEASE_FILE=/etc/openvz-release
else
	echo
  	echo "Error: /etc/redhat-release was not detected"
	echo
	echo "`date -u` ERROR: could not determine release file" >> $LOG
	app_exit 1
fi

# EL5
if egrep -q "release 5|release 2011" $RELEASE_FILE ; then
  DIST="el5"
  DIR=centos/5
# EL6
elif egrep -q "release 6|release 2012" $RELEASE_FILE ; then
  DIST="el6"
  DIR=centos/6
# EL7
elif egrep -q "release 7" $RELEASE_FILE ; then
  	DIST="el7"
  	DIR=centos/7
else
  echo "Error: Unable to determine distribution type. Please send the contents of $RELEASE_FILE to support@atomicorp.com"
  echo "`date -u` ERROR: unable to determine distribution type" >> $LOG
  app_exit 1
fi
echo "`date -u` distribution determined as $DIST" >> $LOG


echo -n "Installing the Atomic GPG key: "
if [ !  -f /etc/pki/rpm-gpg/RPM-GPG-KEY.art.txt ]; then
  	if [ ! -d /etc/pki/rpm-gpg ]; then
    		mkdir -p /etc/pki/rpm-gpg/
  	fi
  	wget -q https://www.atomicorp.com/RPM-GPG-KEY.art.txt -O /etc/pki/rpm-gpg/RPM-GPG-KEY.art.txt  # >> #$LOG 2>&1
	RETVAL=$?
	if [ ! "$RETVAL" = 0 ]; then
        echo FAIL
        echo
        echo "  Could not download the Legacy Atomicorp gpg key"
        echo
        echo "`date -u` ERROR: failed to download the legacy Atomicorp gpg key" >> $LOG
        app_exit 1
	fi
	rm -f RPM-GPG-KEY.art.txt
fi
echo "OK"
/bin/rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY.art.txt
echo "`date -u` legacy Atomicorp GPG key imported" >> $LOG

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
    wget -q https://www.atomicorp.com/RPM-GPG-KEY.atomicorp.txt -O /etc/pki/rpm-gpg/RPM-GPG-KEY.atomicorp.txt  # >> #$LOG 2>&1
    RETVAL=$?
    if [ ! "$RETVAL" = 0 ]; then
        echo FAIL
        wget 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

# tortix.repo
cat << EOF > /etc/yum.repos.d/tortix.repo
# Name: Atomicorp RPM Repository for   -
# URL: http://www.atomicorp.com/
[tortix]
name =  $releasever - atomicorp.com
mirrorlist = file:///var/awp/etc/tortix-mirrorlist
enabled = 1
priority = 1
protect = 0
gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY.atomicorp.txt
gpgcheck = 1

# Almost Stable, release candidates for [tortix]
[tortix-testing]
name =  $releasever - atomicorp.com - (Testing)
mirrorlist = file:///etc/asl/tortix-testing-mirrorlist
enabled = 0
priority = 1
protect = 0
gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY.atomicorp.txt
gpgcheck = 1
EOF

# tortix-kernel.repo
cat << EOF > /etc/yum.repos.d/tortix-kernel.repo
# Name: Atomicorp kernel RPM Repository for   -
# URL: http://www.atomicorp.com/
[tortix-kernel]
name =  $releasever - atomicorp.com
mirrorlist = file:///var/awp/etc/tortix-kernel-mirrorlist
enabled = 0
priority = 1
protect = 0
gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY.atomicorp.txt
gpgcheck = 1

# Almost Stable, release candidates for [tortix-kernel]
[tortix-kernel-testing]
name =  $releasever - atomicorp.com - (Testing)
mirrorlist = file:///var/awp/etc/tortix-kernel-testing-mirrorlist
enabled = 0
priority = 1
protect = 0
gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY.atomicorp.txt
gpgcheck = 1


[tortix-kernel-xen]
name =  $releasever - atomicorp.com
mirrorlist = file:///var/awp/etc/tortix-kernel-xen-mirrorlist
enabled = 0
priority = 1
protect = 0
gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY.atomicorp.txt
gpgcheck = 1

# Almost Stable, release candidates for [tortix-kernel]
[tortix-kernel-xen-testing]
name =  $releasever - atomicorp.com - (Testing)
mirrorlist = file:///var/awp/etc/tortix-kernel-xen-testing-mirrorlist
enabled = 0
priority = 1
protect = 0
gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY.atomicorp.txt
gpgcheck = 1
EOF
#---------------------------------------------------------
echo "`date -u` created .repo files" >> $LOG


# mirrorlist files
#---------------------------------------------------------
cat << EOF > /var/awp/etc/asl-6.0-mirrorlist
https://$USERNAME:$ENCPASSWORD@www4.atomicorp.com/channels/asl-6.0/$DIR/$ARCH
https://$USERNAME:$ENCPASSWORD@www5.atomicorp.com/channels/asl-6.0/$DIR/$ARCH
https://$USERNAME:$ENCPASSWORD@www6.atomicorp.com/channels/asl-6.0/$DIR/$ARCH
https://$USERNAME:$ENCPASSWORD@www7.atomicorp.com/channels/asl-6.0/$DIR/$ARCH
EOF
cat << EOF > /var/awp/etc/asl-6.0-testing-mirrorlist
https://$USERNAME:$ENCPASSWORD@www4.atomicorp.com/channels/asl-6.0-testing/$DIR/$ARCH
https://$USERNAME:$ENCPASSWORD@www5.atomicorp.com/channels/asl-6.0-testing/$DIR/$ARCH
https://$USERNAME:$ENCPASSWORD@www6.atomicorp.com/channels/asl-6.0-testing/$DIR/$ARCH
https://$USERNAME:$ENCPASSWORD@www7.atomicorp.com/channels/asl-6.0-testing/$DIR/$ARCH
EOF
cat << EOF > /var/awp/etc/asl-4.0-mirrorlist
https://$USERNAME:$ENCPASSWORD@www4.atomicorp.com/channels/asl-4.0/$DIR/$ARCH
https://$USERNAME:$ENCPASSWORD@www5.atomicorp.com/channels/asl-4.0/$DIR/$ARCH
https://$USERNAME:$ENCPASSWORD@www6.atomicorp.com/channels/asl-4.0/$DIR/$ARCH
https://$USERNAME:$ENCPASSWORD@www7.atomicorp.com/channels/asl-4.0/$DIR/$ARCH
EOF
cat << EOF > /var/awp/etc/asl-4.0-testing-mirrorlist
https://$USERNAME:$ENCPASSWORD@www4.atomicorp.com/channels/asl-4.0-testing/$DIR/$ARCH
https://$USERNAME:$ENCPASSWORD@www5.atomicorp.com/channels/asl-4.0-testing/$DIR/$ARCH
https://$USERNAME:$ENCPASSWORD@www6.atomicorp.com/channels/asl-4.0-testing/$DIR/$ARCH
https://$USERNAME:$ENCPASSWORD@www7.atomicorp.com/channels/asl-4.0-testing/$DIR/$ARCH
EOF
cat << EOF > /var/awp/etc/tortix-mirrorlist
https://$USERNAME:$ENCPASSWORD@www4.atomicorp.com/channels/tortix/$DIR/$ARCH
https://$USERNAME:$ENCPASSWORD@www5.atomicorp.com/channels/tortix/$DIR/$ARCH
https://$USERNAME:$ENCPASSWORD@www6.atomicorp.com/channels/tortix/$DIR/$ARCH
https://$USERNAME:$ENCPASSWORD@www7.atomicorp.com/channels/tortix/$DIR/$ARCH
EOF
cat << EOF > /var/awp/etc/tortix-kernel-mirrorlist
https://$USERNAME:$ENCPASSWORD@www4.atomicorp.com/channels/tortix-kernel/$DIR/$ARCH
https://$USERNAME:$ENCPASSWORD@www5.atomicorp.com/channels/tortix-kernel/$DIR/$ARCH
https://$USERNAME:$ENCPASSWORD@www6.atomicorp.com/channels/tortix-kernel/$DIR/$ARCH
https://$USERNAME:$ENCPASSWORD@www7.atomicorp.com/channels/tortix-kernel/$DIR/$ARCH
EOF
#---------------------------------------------------------
# HUB Installation
#---------------------------------------------------------

# is this unattended
ESCAPED_PASSWORD=$(echo $PASSWORD | sed -e 's/[\/&]/\\&/g')
if [ ! -f awp.cfg ]; then
	    
	echo "USERNAME=\"$USERNAME\"" >> awp.cfg
	echo "PASSWORD=\"$ESCAPED_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
fi


source ./awp.cfg


echo "`date -u` installing the awp package" >> $LOG
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 install -y $PACKAGES | tee -a $LOG
if [ $? -eq 0 ]; then
   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

    # set username and password in file
    sed -i "s/\"USERNAME\"/\"$USERNAME\"/"  $AWP_CONFIG
    sed -i "s/\"PASSWORD\"/\"$ESCAPED_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 >/dev/null 2>&1
    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
        sed -i "s/\"CONFIGURED\"/\"YES\"/"  /var/awp/etc/config

	echo
	echo "Stopping AWP"
	systemctl stop awpd

	/var/awp/bin/awp_indexgen -f

	echo
	echo "Starting AWP"
	systemctl start awpd

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


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

	if [  -f /etc/httpd/conf.d/welcome.conf ]; then
		rm -f /etc/httpd/conf.d/welcome.conf
	fi

	if pidof httpd >/dev/null; then
		killall -9 httpd >/dev/null 2>&1
	fi

	# 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

	systemctl enable httpd
	systemctl start httpd


	# Issue444
        echo
        echo "Stopping AWP"
        systemctl stop awpd

        /var/awp/bin/awp_indexgen -f

        echo
        echo "Starting AWP"
        systemctl start awpd

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


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

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

    v5Backup
    # Symlink, in case the above fails for some reason, we can revision it
    if [[ -d /etc/asl ]]; then
	mv /etc/asl /etc/asl.upgrade.$(date +%s)
    fi

    # v5 path emulation
    ln -sf /var/awp/etc /etc/asl


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


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