#/bin/bash
# ======================================================================
#
# CLEANUP script to remove services on a host if a service was deleted
# in LDAP
#
# IML specific: uses puppet to recreate all checks
#
# script is started as cron
# ----------------------------------------------------------------------
# 2020-03-06  v0.1  <axel.hahn@iml.unibe.ch>
# 2020-03-09  v0.2  <axel.hahn@iml.unibe.ch>  waiting for pupet puppet
# ======================================================================

. `dirname $0`/inc_getconfig.sh || exit 1

dirWithChecks=${dir_cfg}/checks/
lockfile="${dir_data}/`basename $0`.pid"

typeset -i iCounter=0
typeset -i iMaxWait=120

# ----------------------------------------------------------------------
# MAIN
# ----------------------------------------------------------------------

if [ ! -d ${dirWithChecks} ]; then
    echo ERROR: directory witch check configs does not exist [$dirWithChecks]
    exit 1
fi


if [ -f "${lockfile}" ]; then
    lockpid=`cat "${lockfile}" | cut -f 2 -d "-" | cut -f 4 -d " " | grep "[0-9]"`
    ps -f --pid $lockpid >/dev/null
    if [ $? -eq 0 ]; then
        _log "ABORT: update seems to run already. See process with PID $lockpid"
        echo
        ps -f --pid $lockpid
        echo
        exit 0
    fi
fi
echo "cleanup services started `date` - process id $$" > "${lockfile}"


echo --- 1/3 :: DELETE all existing configs
ls -l ${dir_cfg}/checks/*
rm -f ${dir_cfg}/checks/*
echo
echo directory content after deletion:
ls -l ${dir_cfg}/checks/*
echo


echo --- 2/3 :: WAITING max $iMaxWait min for a puppet run to recreate the checks
rc=1
while [ $rc -ne 0 ]; do
    ls -l ${dir_cfg}/checks/* >/dev/null 2>&1
    rc=$?
    if [ $rc -ne 0 ]; then
        iCounter=$iCounter+1
        echo -n "$iCounter ... `date` - "
        if [ $iCounter -gt $iMaxWait ]; then
            echo "ERROR: puppet did not start within $iMaxWait min??? ABORTING here."
            exit 1
        fi
        echo "waiting ..."
        sleep 60
    fi
done
echo "Found :-)"
echo

echo --- 3/3 :: CLEANUP links on icinga
`dirname $0`/director-cli.sh --linkcleanup
echo


echo --- DONE
rm -f $lockfile
exit 0

# ----------------------------------------------------------------------