#!/bin/bash
# Start/stop chronyd
# chkconfig:   - 59 41
# description: Client/server for the Network Time Protocol, \
#              this program keeps your computer's clock accurate.

### BEGIN INIT INFO
# Provides: chronyd
# Required-Start: $network $local_fs $remote_fs
# Required-Stop: 
# Should-Start: $syslog $named
# Should-Stop: $syslog
# Short-Description: NTP client/server
# Description: Client/server for the Network Time Protocol,
#              this program keeps your computer's clock accurate.
### END INIT INFO

# Source function library.
. /etc/rc.d/init.d/functions

# Source networking configuration.
. /etc/sysconfig/network

exec=/usr/sbin/chronyd
prog=chronyd
config=/etc/chrony.conf
keyfile=/etc/chrony.keys
chronyc=/usr/bin/chronyc
dhclient_servers=/var/lib/dhclient/chrony.servers.*
conflicts="ntpd"

[ -e /etc/sysconfig/$prog ] && . /etc/sysconfig/$prog

lockfile=/var/lock/subsys/$prog

chrony_command() {
    $chronyc -a <<EOF | grep -v '200 OK'
$1
EOF
    return ${PIPESTATUS[0]}
}

add_dhclient_servers() {
    command=$(cat $dhclient_servers 2> /dev/null |
        while read server serverargs; do
            echo "add server $server $serverargs"
        done)
    if [ -n "$command" ]; then
        echo -n $"Adding dhclient NTP servers to chrony: "
        chrony_command "$command" &> /dev/null && success || failure
        echo
    fi
}

start() {
    [ "$NETWORKING" = "no" ] && exit 1
    [ -x $exec ] || exit 5
    [ -f $config ] || exit 6

    for s in $conflicts; do
        status -p /var/run/$s.pid $s >/dev/null 2>&1 || continue
        echo "Conflicting service $s is already running. Cannot start $prog."
        exit 1
    done

    echo -n $"Starting $prog: "
    daemon $exec $OPTIONS
    retval=$?
    echo
    [ $retval -eq 0 ] && touch $lockfile
    [ $retval -eq 0 ] && add_dhclient_servers
    return $retval
}

stop() {
    echo -n $"Stopping $prog: "
    killproc $prog
    retval=$?
    echo
    [ $retval -eq 0 ] && rm -f $lockfile
    return $retval
}

restart() {
    stop
    start
}

reload() {
    restart
}

force_reload() {
    restart
}

rh_status() {
    status $prog
}

rh_status_q() {
    rh_status >/dev/null 2>&1
}


case "$1" in
    start)
        rh_status_q && exit 0
        $1
        ;;
    stop)
        rh_status_q || exit 0
        $1
        ;;
    restart)
        $1
        ;;
    reload)
        rh_status_q || exit 7
        $1
        ;;
    force-reload)
        force_reload
        ;;
    status)
        rh_status
        ;;
    condrestart|try-restart)
        rh_status_q || exit 0
        restart
        ;;
    online|offline|cyclelogs)
        rh_status_q || exit 7
        chrony_command $1
        ;;
    command)
        rh_status_q || exit 7
        chrony_command "$2"
        ;;
    *)
        echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|cyclelogs|online|offline|command}"
        exit 2
esac
exit $?

