#!/bin/sh

###############################################################################
#
# /etc/init.d/sys - System control script for the sys daemon.
# Also accessed via a symbolic link named /usr/local/sbin/rcsysd.
#
# Copyright (c) 2006, all rights reserved
# License- GPL
# Author-  Jeremy P Thien
# Company- Adtec Digital, Inc.
# Date-    2006-06-06
#
###############################################################################

readonly DAEMON="/usr/local/sbin/ntpd"
readonly CONF="/etc/ntp.conf"
readonly NTPDATE="/usr/sbin/ntpdate"
readonly NTPD_DIR="/var/ntp/"
readonly PID_FILE="/var/run/ntpd.pid"
readonly OPTIONS="-- -p ${PID_FILE}"   #store pid file in specified directory and run as ntp user

# Indicate whether reloads are supported via signals (usually SIGHUP (1)).
# If so, define RELOAD_SIGNAL to the signal. If not, comment out.
#RELOAD_SIGNAL="1"

# Include the common script for all service scripts.
source /etc/init.d/rcservices


#------------------------------------------------------------------------------
# extract the ntp server address from conf
function get_ntp_server () {
  # AUTO: Try to get server from config file
  if [ -r $CONF ] ; then 
    LINE=$(/bin/grep -m 1 "^[ ]\{0,\}server" $CONF | sed 's/^[ \t]*//')
    echo $LINE | cut -d" " -f2
  fi
}

#------------------------------------------------------------------------------
# Start the service.
do_start ()
{
  local NTPDATE_FROM=`get_ntp_server`
  if [ -n "$NTPDATE_FROM" -a -x $NTPDATE ]; then
    echo "Try to get initial date and time via NTP from $NTPDATE_FROM"
  $NTPDATE $NTPDATE_FROM | logger -t ' [NTPDATE]'
  if [ $? -ne 0 ]; then
    logger -t ' [NTPDATE]' "Failed to get initial time from ntp server"
    RESULT=$FAILED
   else
      echo -n "Starting $DAEMON daemon "
      start-stop-daemon --quiet --start --exec $DAEMON $OPTIONS
      case $? in
        0) RESULT=$SUCCESS;;             # Started OK
        1) RESULT=$PROGRAM_IS_RUNNING;;  # Already running
        *) RESULT=$FAILED;;              # Trouble
      esac
      print_result
    fi
  else
    logger -t '   [NTPD]' "No valid NTPD configuration found."
    RESULT=$FAILED
  fi
  return $RESULT
}

#------------------------------------------------------------------------------
# Stop the service.
do_stop ()
{
  echo -n "Stopping $DAEMON daemon "
  start-stop-daemon --quiet --stop --exec $DAEMON
  case $? in
    0) RESULT=$SUCCESS;;              # Stopped OK
    1) RESULT=$PROGRAM_NOT_RUNNING;;  # No process running
    *) RESULT=$FAILED;;               # Trouble
  esac
  print_result
  return $RESULT
}

# Do the service.
dispatch_service $1
