#!/bin/sh
### BEGIN INIT INFO
# Provides:            ntp
# Required-Start:      $network $syslog
# Required-Stop:       $network $syslog
# Should-Start:
# Should-Stop:
# Default-Start:       3 4 5
# Default-Stop:        0 1 2 6
# Short-Description:   NTP Daemon
### END INIT INFO

. /lib/lsb/init-functions

DAEMON=/usr/sbin/ntpd
PIDFILE=/var/run/ntpd.pid

case "$1" in
  start)
    log_init_msg "Starting NTP server"
    start_daemon -p "$PIDFILE" "$DAEMON" "-p $PIDFILE -g -u 87:87" \
      && log_success_msg || log_failure_msg
    ;;
  stop)
    pid=$(pidofproc -p "$PIDFILE" "$DAEMON")

    if [ "$?" -ne 0 ]; then
      log_init_msg "NTP server not running" && log_success_msg
      exit 0
    fi

    log_init_msg "Stopping NTP server"

    killproc -p "$PIDFILE" "$DAEMON" -TERM && log_success_msg \
      || log_failure_msg
    ;;
  reload|restart)
    log_init_msg "Restarting NTP server"

    killproc -p "$PIDFILE" "$DAEMON" -HUP && log_success_msg \
      || log_failure_msg
    ;;
  status)
    pid=$(pidofproc -p "$PIDFILE" "$DAEMON")

    if [ "$?" -ne 0 ]; then
      echo "NTP server not running"
    else
      echo "NTP server running with PID: $pid"
      /usr/sbin/ntpq -pn
    fi
    ;;
  *)
    echo "Usage: $0 [start|stop|reload|restart|status]"
    exit 1
    ;;
esac

exit 0
