#! /bin/sh
#
# Written by Miquel van Smoorenburg <miquels@drinkel.ow.org>.
# Modified for Debian GNU/Linux by Ian Murdock <imurdock@gnu.ai.mit.edu>.
# Modified for Debian by Christoph Lameter <clameter@debian.org>
# Modified for chrony by John Hasler <jhasler@debian.org> 1998-2012
# Modified for Debian by Vincent Blut <vincent.debian@free.fr>

### BEGIN INIT INFO
# Provides:          chrony
# Required-Start:    $remote_fs
# Required-Stop:     $remote_fs
# Should-Start:      $syslog $network $named $time
# Should-Stop:       $syslog $network $named $time
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Controls chronyd NTP time daemon
# Description:       Chronyd is the NTP time daemon in the Chrony package
### END INIT INFO

PATH=/bin:/usr/bin:/sbin:/usr/sbin
DAEMON=/usr/sbin/chronyd
NAME="chronyd"
DESC="time daemon"

[ -x "$DAEMON" ] || exit 0

. /lib/lsb/init-functions

# Override this variable by editing /etc/default/chrony.
DAEMON_OPTS=""
if [ -f /etc/default/chrony ]; then
    . /etc/default/chrony
fi

putonline ()
{   # Do we have a default route?  If so put chronyd online.
    if ip r 2>/dev/null | grep -q '^default'; then
        if chronyc -m online 'burst 4/4' > /dev/null 2>&1; then
            touch /var/run/chrony-ppp-up
            echo "$NAME is running and online."
        else
            rm -f /var/run/chrony-ppp-up
            echo "$NAME is running and offline."
        fi
    else
        rm -f /var/run/chrony-ppp-up
        echo "$NAME is running and offline."
    fi
}

case "$1" in
    start)
	start-stop-daemon --start --verbose --exec $DAEMON -- $DAEMON_OPTS
	case "$?" in
		0) # daemon successfully started
			putonline
			;;
	        1) # daemon already running
		        ;;
		*) # daemon could not be started
			echo "$DAEMON failed to start."
			exit 1
			;;
	esac
	;;
    stop)
	start-stop-daemon --stop --verbose --oknodo --exec $DAEMON
	rm -f /var/run/chrony-ppp-up
	;;
    restart|force-reload)
	echo -n "Restarting $DESC: "
	start-stop-daemon --stop --quiet --exec $DAEMON
	sleep 1
	start-stop-daemon --start --verbose --exec $DAEMON -- $DAEMON_OPTS
	case "$?" in
		0) # daemon successfully started
			putonline
			;;
	        1) # still running
		        ;;
		*) # daemon could not be started
			echo "$DAEMON failed to restart."
			rm -f /var/run/chrony-ppp-up
			exit 1
			;;
	esac
	;;
    status)
	status_of_proc "$DAEMON" "$NAME" && exit 0 || exit $?
	;;
    *)
	echo "Usage: /etc/init.d/chrony {start|stop|restart|force-reload|status}"
	exit 1
	;;
esac

exit 0
