#! /bin/sh
#
# System-V init script for the cron
#

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DESC="cron daemon"
NAME=crond
DAEMON=/usr/sbin/$NAME

# Gracefully exit if the package has been removed.
test -x $DAEMON || exit 0

splitCrontab() {
    # TODO proper fix
    # This is workaround, not sure if it is secure
    # Allow root to execute only [/root/*] and [su martem -c '*']
    local filter='/usr/local/bin/gwconf-files/filters/crontab.awk'
    local tmp="$(mktemp -t crontab-tmp.XXXXXX)"
    "$filter" -v nomatch="${tmp}" '/etc/crontab' | crontab -u root -
    if [ -s "${tmp}" ]; then
        logger -s -p "user.warn" -t "$0" "Some lines removed from root crontab"
        # non-matching to martem user (may not execute)
        cat "${tmp}" | crontab -u martem -
    fi
    rm "${tmp}"
}

setup_crontab() {
    # busybox crond want's username's crontab in /var/spool/cron/crontabs/username
    mkdir -p '/var/spool/cron/crontabs'
    if true; then
        splitCrontab
    else
        # Preserve root crontab from standard place
        cp '/etc/crontab' '/var/spool/cron/crontabs/root'
    fi
}

start() {
    if [ -r /etc/crontab ]; then
        logger -s -p "user.info" -t "$0" "Starting cron service"

        setup_crontab

        logger -s -p "user.info" -t "$0" "Starting $DESC: $NAME"
        $DAEMON
    fi
}
stop() {
    logger -s -p "user.info" -t "$0" "Killing cron service"
    busybox killall -9 $NAME
}
restart() {
    stop
    start
}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart|reload)
        restart
        ;;
    *)
        echo "Usage: $0 {start|stop|restart}"
        exit 1
esac

exit $?
