#!/bin/sh
#
# ntpdate - emulate the crufty old ntpdate utility from NTP Classic
#
# Not documented, as this is strictly a backward-compatibility shim. It's
# based on the recipes at
#           http://support.ntp.org/bin/view/Dev/DeprecatingNtpdate
# with corrections for modern ntpdig options.
#
# Debug this by giving the -n option, which causes it to echo the
# generated ntpdig command rather than executing it.
#
# Known bugs:
# * The -e and -p options of ntpdate are not yet implemented.
# * ntpdate took 4 samples and chose the best (shortest trip time).
#   This takes the first.
#
# ntpdate ntpdig  ntpd    What it does
# -4      -4      -q -4   Resolve DNS lookups to A records         
# -6      -6      -q -6   Resolve DNS lookups to AAAA records      
# -a N    -a N    -q      Authentication   
# -b      -S      -q      step time adjustments
# -B      -s      -q      slew time adjustments
# -d      -d      -d      debugging mode (implies -q)
# -e N.N          -q      authdelay        
# -k file -k file -k file key file         
# -o N    -o N    -q      NTP Protocol version
# -p N            -q      How many samples to take
# -q      default -q      query/report only, don't set clock
#                         (implies -u for ntpdate)
# -s                      log to syslog (always enabled in ntpd)
# -t N.N  -t N.N          request timeout
# -u      default         unpriv port      
# -v                      verbose (ntpd is always more verbose than ntpdate)
#         -c name         Send concurrent requests to resolved IPs for name
#   
#         -l file         Log to file
#         -M msec         Slew adjustments less than msec,
#                         step adjustments larger than msec.       
#
# SPDX-License-Identifier: BSD-2-Clause

PASSTHROUGH=""
TIMEOUT="-t 1"
setclock=yes
echo=no
log=no
while getopts 46a:bBe:k:no:p:qst:uv opt
do
    case $opt in
	4) PASSTHROUGH="$PASSTHROUGH -4";;
	6) PASSTHROUGH="$PASSTHROUGH -6";;
	a) PASSTHROUGH="$PASSTHROUGH -a $OPTARG";;
	b) ADJUST="$ADJUST -S";;
	B) ADJUST="$ADJUST -s";;
	d) PASSTHROUGH="$PASSTHROUGH -d";;
	e) echo "ntpdate: -e is no longer supported." >&2;;
	k) PASSTHROUGH="$PASSTHROUGH -k $OPTARG";;
	n) echo=yes;;			# Echo generated command, don't execute
	o) PASSTHROUGH="$PASSTHROUGH -o $OPTARG";;
	p) echo "ntpdate: -p is no longer supported." >&2;;
	q) setclock=no;;
	s) log=yes;;
	t) PASSTHROUGH="$PASSTHROUGH -t $OPTARG"; TIMEOUT="";;
	u) ;;
	v) ;;
    esac
done
shift $(($OPTIND - 1))

if [ "$setclock" = yes -a -z "$ADJUST" ]
then
    ADJUST="-s -j"
fi

if [ "$echo" = yes ]
then
    echo ntpdig $ADJUST $TIMEOUT $PASSTHROUGH $*
else
    if [ "$log" = yes ]
    then
        ntpdig $ADJUST $TIMEOUT $PASSTHROUGH $* 2>&1 | logger -t ntpdate
    else
        ntpdig $ADJUST $TIMEOUT $PASSTHROUGH $*
    fi
fi

#end

