#!/usr/bin/bash

set -eo pipefail

# Main, main
startdir=$PWD
cmd=`basename $0`
basedir=`dirname $0`

if [ `whoami` != "root" ]; then
  echo "Error: You need to be root to run $cmd"
  echo "Usage: $cmd [--help|-h] [--verbose|-v] [--debug|-d]"
  exit 1
fi

while [ -n "$1" ]; do
case $1 in
  --help|-h) echo "Usage: $cmd [--help|-h] [--verbose|-v] [--debug|-d]"
    echo "      --help|-h     prints this text"
    echo "      --verbose|-v  Ansible with --verbose option. Log to terminal"
    echo "      --debug|-d    Ansible with --debug option"
    echo ""
    shift
    exit 0
    ;;
  --verbose|-v)
    verbose="--verbose"
    shift
    ;;
  --debug|-d)
    debug="--debug"
    shift ;;
   *)
    echo "Usage: $cmd [--help|-h] [--verbose|-v] [--debug|-d]"
    exit 1
    ;;
esac
shift
done

if [ -n "$ANSIBLE_BASEDIR" ]; then
    basedir="$ANSIBLE_BASEDIR"
fi

cd $basedir

if [ -z ${LOGFILE} ]; then
	LOGFILE=/tmp/elt-ansible-`date +%Y%m%d`.log
fi

## Start a progress indicator
if [ "$verbose" == "--verbose" ]; then
  export ANSIBLE_VERBOSITY=1
fi

if [ "$debug" == "--debug" ]; then
  export ANSIBLE_VERBOSITY=3
fi

echo "Update/Installation started, please wait...."
echo "The procedure may take a very long time to complete"
date=
echo "You can follow the installation-logfile in another terminal with the command:"
echo "        tail -f ${LOGFILE}"
echo ""
export ANSIBLE_LOG_PATH=${LOGFILE}
sudo -E  ansible-playbook -i localhost devenv.yml
ANSIBLERC=$?

cd $startdir

echo
echo "Ansible detailed exit code = ${ANSIBLERC}" | tee -a ${LOGFILE}
if [ "${ANSIBLERC}" -ne "0"  ]; then
  echo
  echo "Ansible exit code indicates a possible problem in the execution."
  echo "Please check the installation log file in ${LOGFILE} and/or contact ELTMGR"
  echo
  exit 1
fi

WAFCACHEDIR="/var/cache/wafcache/global"
if [ -d ${WAFCACHEDIR} ]; then
  echo
  echo "Cleaning up global wafcache directory (${WAFCACHEDIR})!"
  rm -rf ${WAFCACHEDIR}/*
fi

if [ "${ELT_ROLE}" != "MINIMAL" ]; then
  # Update motd
  /root/bin/eltdev-status.sh > /etc/motd
fi


echo
echo "Ansible exit code indicates a succesfull execution!"
#Remove ANSIBLE config vars from environment
unset ANSIBLE_LOG_PATH ANSIBLE_VERBOSITY
exit 0
