#!/bin/sh

#------------------------------------------------------------------------------
#
# A simple service watcher.
#
#------------------------------------------------------------------------------

PIDOF="/sbin/pidof"
LOGGER="/usr/bin/logger -p local6.notice -t servicewatch"
DAEMONS="\
slapd|slapd \
webconfig|webconfig \
clearsync|clearsyncd \
suvad|suvad \
vpnwatchd|vpnwatchd \
syswatch|syswatch \
snortsam|snortsam \
snort|snort \
eziod|eziod \
ibvpn|ibvpn \
zarafa-dagent|zarafa-dagent \
zarafa-gateway|zarafa-gateway \
zarafa-ical|zarafa-ical \
zarafa-licensed|zarafa-licensed \
zarafa-monitor|zarafa-monitor \
zarafa-presence|zarafa-presence \
zarafa-server|zarafa-server \
zarafa-spooler|zarafa-spooler \
"

CHECK_BACKUP=`$PIDOF -x configuration-restore`
if [ -n "$CHECK_BACKUP" ]; then
    $LOGGER "waiting on configuration restore"
    exit 0
fi

for DAEMON in $DAEMONS; do
    SERVICE=`echo $DAEMON | cut -d '|' -f 1`
    PROCESS_NAME=`echo $DAEMON | cut -d '|' -f 2`
    IS_ENABLED=`systemctl is-enabled $SERVICE 2>/dev/null | grep enabled`

    if [ -n "$IS_ENABLED" ]; then
        PID=`$PIDOF $PROCESS_NAME`
        if [ "$PID" == "" ]; then
            $LOGGER "sanity checking $SERVICE"
            sleep 30
            PID=`$PIDOF $PROCESS_NAME`
            if [ "$PID" == "" ]; then
                /usr/sbin/service $SERVICE stop
                sleep 2
                /usr/sbin/service $SERVICE start
                $LOGGER "restarting $SERVICE"
            fi
        fi
    fi
done
