#!/bin/bash
# NTP time synchronization start up and stop script.
#
# locations of various things.
NTPBIN="/usr/sbin"
NTPDATE="$NTPBIN/ntpdate"
NTPD="$NTPBIN/ntpd"
NTPDLOG="/var/log/ntpd"
NTPCONF="/etc/ntp.conf"
SERVERS="194.109.22.18 195.13.1.153"


GREP="/usr/bin/grep"
PS="/bin/ps ax"
SED="/usr/bin/sed"

case "$1" in
    'start')
        # Is ntpd already running? More than once?
        pidlist=`$PS | $GREP ntpd | $GREP -v grep | $SED -e 's/^  *//' -e 's/ .*//'`
        for pid in $pidlist ; do
            if [ $pid -ne 0 ]; then
                echo "Warning: $NTPD already running!"
                exit 1
            fi
        done

        if [ -x $NTPDATE ] ; then
            echo "Setting date with ntpdate..."
            $NTPDATE -b -s $SERVERS
            sleep 3 # wait till it settles down?
        fi

        if [ -x $NTPD ] ; then
          # Now start ntpd --- and you thought I'd never get around to it!
            echo "Starting ntpd daemon..."
            if [ -w $NTPDLOG ] ; then
                $NTPD -c $NTPCONF -l $NTPDLOG
            else
                $NTPD -c $NTPCONF
            fi
            exit $?
        else
            echo "${0}: ntpd (in ${NTPD}) not found or not executable."
        fi
        ;;
    'stop')
        # Is ntpd already running? More than once?
        pidlist=`$PS | $GREP ntpd | $GREP -v grep | $SED -e 's/^  *//' -e 's/ .*//'`
        for pid in $pidlist ; do
            if [ $pid -ne 0 ]; then
                echo "Killing ntpd daemon with pid $pid..."
                kill $pid
            fi
        done
        exit $?
        ;;
    *)
        echo "Usage: $0 { start | stop }"
        exit 1
        ;;
esac
exit 0


