#!/bin/sh

_keyfile=/opt/etc/ntp.keys
_ipaddress=""
_truestedkey=""

log_file=/var/log/ntpd.log

/bin/rm -f $log_file

one_file_line_check_test() {
  if [ "$1" = "trustedkey" ] ; then
    _truestedkey=$2
    return
  fi
  if [ ! "$1" = "server" ] ; then
    return
  fi
  if [ "$1" = "server" ] ; then  
    _ipaddress=$2
  fi
}

file_check_test() {
  file_length=`/opt/bin/wc -l $1 | cut -f1 -d ' '`   # Count Lines
  file_length=`expr $file_length + 0`     # Change Type
  while [ 1 = 1 ] ; do
      line=`head -$file_length $1 | tail -1` # Get Line
      if [ ! "`echo $line | grep -v \# `" = "" ] ; then
        #echo $line
        one_file_line_check_test $line
      fi
      if [ $file_length = 0 ] ; then break ; fi
      file_length=`expr $file_length - 1`
  done
}


file_check_test /opt/etc/ntp.conf

if [ "$_truestedkey" = "" ] ; then
  /opt/bin/ntpdate -u -b  $_ipaddress > $log_file
else 
  /opt/bin/ntpdate -u -k $_keyfile -b -a $_truestedkey $_ipaddress > $log_file
fi

return_code=$?

the_date=`date +" %d %b %H:%M:%S"`


if [ "$return_code" = "0" ] ; then
  echo "$the_date ntpd[----]: NTP server contacted at startup" >$log_file
else 
  echo "$the_date ntpd[----]: NTP server not contacted at startup" >$log_file
  /nn/bin/AddNnuDiagLog -mNTP -ltimeanddate.log -wE -v6008 "Cannot contact NTP server" 
fi

/opt/bin/ntpd -l /var/log/ntpd.log -c /opt/etc/ntp.conf 

