#! /bin/bash

NAME=xntpd
DAEMON=/usr/sbin/$NAME

# for "daemon" and "killproc"
. /etc/rc.d/init.d/functions

case "$1" in
 start)
  [ ! -e $SVIlock ] || exit 1

  echo -n "Starting time synchronization (NTP): "

  eval `perl -ne '
    if ( s/^server\s*(\S+)\s.*$/$1/ ) {
      /^127\.127\.1\./ || push @S, $_;
      /^127\.127\./ || push @NS, $_;
    } elsif ( s/^peer\s+(\S+)(\s.*|)$/$1/ ) {
      /^127\.127\./ || push @NP, $_;
    } else {
      /^broadcastclient/ && push @BC, $_;
      /^mu-v lticastclient/ && push @MC, $_;
    }
    sub END() {
      print "SERVERS=\"", join(" ",@S), "\"\n" if (@S);
      print "NETSERVERS=\"", join(" ",@NS), "\"\n" if @NS;
      print "NETPEERS=\"", join(" ",@NP), "\"\n" if @NP;
      print "BCC=\"", join(" ",@BC), "\"\n" if @BC;
      print "MCC=\"", join(" ",@MC), "\"\n" if @MC;
    }' /etc/ntp.conf`

  # Acquire initial time setting if available
  if [ -x /usr/sbin/ntpdate ] && [ -n "$NETSERVERS$NETPEERS" ]; then
    SVIrun S I " (ntpdate)" " (!ntpdate)" \
    /usr/sbin/ntpdate -bs $NETSERVERS $NETPEERS
  fi

  # Do we have a reference clock?
  [ -n "$SERVERS$NETPEERS$BCC$MCC" ] || exit 2

  # Start daemon.
  ssd -S -n $NAME -x $DAEMON -- -p /var/run/$NAME.pid $OPTIONS

  echo "."
  touch $SVIlock
  ;;

 stop)
  [ -e $SVIlock ] || exit 0
  # Stop daemon.
  echo -n "Shutting down xntpd: "
  ssd -K -p /var/run/$NAME.pid -n $NAME
  
  echo "."
  rm -f $SVIlock
  ;;

 *)
  echo "Usage: ntp {start|stop}"
  exit 1
  ;;
esac

exit 0
