#!/usr/bin/bash

# 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  Puppet with --verbose option. Log to terminal"
    echo "      --debug|-d    Puppet 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 "$PUPPET_BASEDIR" ]; then
    basedir="$PUPPET_BASEDIR"
fi

cd $basedir



# Reexport some vars as facts to make configuration easier
export FACTER_ELT_ROLE=${ELT_ROLE}
if [ -z "$ELT_DM" ]; then
  export FACTER_ELT_DM=no
else
  export FACTER_ELT_DM=${ELT_DM}
fi

export FACTER_ELT_RELEASE=`rpm -q --qf '%{version}-%{release}' elt-devenv-release`
# Strip all version suffixes like ~alpha, ~beta, ^1.g015b0b19 etc from the version number
export FACTER_ELT_REPO=`rpm -q --qf '%{version}' elt-devenv-release | grep -o '^[^~^]*'`

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

## Start a progress indicator
if [ "$verbose" == "--verbose" ]; then
  touch ${LOGFILE}
  tail -f ${LOGFILE} &
  tailid=$!
fi

## Start a progress indicator
while :; do
  sleep 5
  printf "."
done &
## store the background process's ID
bgid=$!

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 ""
sudo -E /usr/bin/puppet apply --detailed-exitcodes $verbose $debug --config "./puppet/puppet.conf" -l ${LOGFILE} "./puppet/manifest/" --disable_warnings deprecations
PUPPETRC=$?

kill "$bgid"
wait "$bgid" 2>/dev/null
if [ -n "$tailid" ]; then
  kill "$tailid"
  wait "$tailid" 2>/dev/null
fi

cd $startdir

echo
echo "Puppet detailed exit code = ${PUPPETRC}" | tee -a ${LOGFILE}
if [ "${PUPPETRC}" -ne "0"  ] && [ "${PUPPETRC}" -ne "2" ]; then
  echo
  echo "Puppet 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

if [ "${PUPPETRC}" -eq "2"  ] || [ "${PUPPETRC}" -eq "6" ]; then
  WAFCACHEDIR="/var/cache/wafcache/global"
  if [ -d ${WAFCACHEDIR} ]; then
    echo
    echo "Puppet detected changes, 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
fi

echo
echo "Puppet exit code indicates a succesfull execution!"

exit 0
