#!/bin/sh
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
echo "WARNING WARNING WARING"
echo "  This script has been deprecated for: awp-hub"
echo "WARNING WARNING WARNING"
echo
echo
echo
echo "Hit any key to continue"
read < /dev/tty

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 v5CronRemoval {
# pulled from cron files listed in asl spec file
files=(
	"/etc/cron.daily/asl-webapp-inventory"
	"/etc/cron.daily/rblcheck"
	"/etc/cron.daily/dynamic_ip_whitelist"
	"/etc/cron.weekly/asl-webapp-inventory"
	"/etc/cron.daily/asl"
	"/etc/cron.hourly/asl"
	"/etc/cron.weekly/asl"
	"/etc/cron.monthly/asl"
	"/etc/cron.d/asl-repsend"
)

for file in "${files[@]}"; do
	if [ -f $file ]; then
		rm -f $file
	fi
done
}

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
		/usr/bin/cp -rf /etc/asl /etc/asl.backup
	fi
}



# Main

# take care of v5 related things first
if isV5Installed; then
	v5CronRemoval
	v5Backup
fi

# 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
    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
  	echo "`date -u` credentials derived from /var/awp/etc/tortix.key " >> $LOG
  	TC_TARGET="www.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="www.atomicorp.com/channels/asl-3.0/README"
		echo -n "Enter subscription Username: "
		read USERNAME < $INSTALL_TTY
		export USERNAME
		echo "Username: $USERNAME" #>> #$LOG

		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://www.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=0
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
#---------------------------------------------------------

echo "`date -u` installing the awp package" >> $LOG
yum install -y awp awp-web | tee -a $LOG
if [ $? -eq 0 ] ; then
    # 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
	ESCAPED_PASSWORD=$(echo $PASSWORD | sed -e 's/[\/&]/\\&/g')
	sed -i "s/\"USERNAME\"/\"$USERNAME\"/"  /var/awp/etc/config
	sed -i "s/\"PASSWORD\"/\"$ESCAPED_PASSWORD\"/"  /var/awp/etc/config

    echo "`date -u` updated /var/awp/etc/config" >> $LOG

    echo "`date -u` running /var/awp/bin/setup" >> $LOG
	/var/awp/bin/setup | 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

		echo
		echo "Starting AWP"
		systemctl start awpd

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

		echo
        echo "Access the AWP web console at https://<your_ip>:30001"
    fi
else
	echo "There was a problem with the Yum installation"
	echo "`date -u` ERROR: base package installation failed" >> $LOG
	app_exit 1
fi


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