#!/bin/sh

##
## This script controls push notification delivery cron job
##

if [ "$#" -lt 1 ]; then
    echo "USAGE: $0 <on|off|status> [interval]";
    echo "  interval could be integer value between 1 and 60, it specified execution period in minutes. 5 is default.";
    exit 1;
fi;

#set -e;

ACTION=${1:-off}
INTERVAL=${2:-5}
USER="psaadm";

CRON_COMMAND="/usr/local/psa/bin/sw-engine-pleskrun /usr/local/psa/admin/plib/modules/plesk-mobile/push/worker.php"

if [ "${ACTION}" = "on" ]; then
    if crontab -u ${USER} -l 2>/dev/null | grep -q "${CRON_COMMAND}"; then
        echo 'WARNING: Cron job already exists';
    else
        tmp=$(tempfile);
        crontab -l -u ${USER} 2>/dev/null > "${tmp}";
        echo "*/${INTERVAL} * * * *         ${CRON_COMMAND}" >> "${tmp}";
        crontab -u "${USER}" "${tmp}";
        rm "${tmp}";
        echo 'INFO: Cron job was successfully added';
    fi;

    exit 0;
fi;

if [ "${ACTION}" = "status" ]; then
    if crontab -u ${USER} -l 2>/dev/null | grep -q "${CRON_COMMAND}"; then
        echo 'INFO: Enabled';
    else
        echo 'INFO: Disabled';
    fi;

    exit 0;
fi;

if [ "${ACTION}" = "off" ]; then
    if crontab -u ${USER} -l 2>/dev/null | grep -q "${CRON_COMMAND}"; then
        crontab -u "${USER}" -l | grep -v "${CRON_COMMAND}" | crontab -u "${USER}" -;
        echo 'INFO: Cron job was successfully removed';
    else
        echo "WARNING: Cron job doesn't exist";
    fi;

    exit 0;
fi;

echo "ERROR: Unknown command ${ACTION}.";
exit 1;