#!/bin/bash
# 
# Start only if Crontab is enabled
. /omd/sites/monitor/etc/omd/site.conf
if [ "$CONFIG_CRONTAB" != on ] ; then
    exit 5
fi

NAME="crontab"
MERGECRONTABS="/omd/sites/monitor/bin/merge-crontabs"
CROND="/omd/sites/monitor/etc/cron.d/*[^~]"
CRONTAB=`which crontab`          
CRONTAB_OPTS=""
USER="monitor"

# check for root
if [ $(id -un) != "$USER" ]; then
    echo "must be run as site user"
	exit 1
fi

# See how we were called.
case "$1" in

    start)
	echo -en "Initializing Crontab..."
	${MERGECRONTABS} ${CROND} | $CRONTAB $CRONTAB_OPTS - > /dev/null
        if [ $? -eq 0 ]; then
            echo "OK"
            exit 0
	else
	    echo "ERROR"
	    exit 1
        fi
        ;;

    stop)
        echo -n "Removing Crontab..."
        $CRONTAB $CRONTAB_OPTS -l >/dev/null 2>&1
        if [ $? -eq 0 ]; then
            $CRONTAB $CRONTAB_OPTS -r
        else
            echo -n "(already empty)..."
        fi
        echo OK
        exit 0
        ;;

    restart|reload)
        $0 stop
        $0 start
        ;;
    status)
        $CRONTAB $CRONTAB_OPTS -l >/dev/null 2>&1
        if [ $? -eq 0 ]; then
            echo "crontab initialized"
            exit 0
        else
            echo "crontab is empty"
            exit 1
        fi
        ;;
    check)
        ;;
    *)
        echo "Usage: crontab {start|stop|restart|reload|status}"
        exit 1
        ;;

esac
  
# End of this script
