#!/bin/sh
# Output is in seconds

PATH=$PATH:/usr/bin:/usr/sbin
export PATH

while true
do
 ntpq -pn | grep "^*" > /dev/null 2>&1
 if [ $? -eq 0 ];then
   offset=`ntpq -np | grep '^*'| cut -c 2- |awk '{print $1}' |xargs ntpdate -q 2>/dev/null |head -1 |awk -F, '{print $3}'|awk '{print $2}'`
   break
 fi

 ntpq -pn | grep "^#" > /dev/null 2>&1
 if [ $? -eq 0 ];then
   offset=`ntpq -np | grep '^#'| cut -c 2- |awk '{print $1}' |xargs ntpdate -q 2>/dev/null |head -1 |awk -F, '{print $3}'|awk '{print $2}'`
   break
 fi

 ntpq -pn | grep "^+" > /dev/null 2>&1
 if [ $? -eq 0 ];then
   offset=`ntpq -np | grep '^+'| cut -c 2- |awk '{print $1}' |xargs ntpdate -q 2>/dev/null |head -1 |awk -F, '{print $3}'|awk '{print $2}'`
   break
 fi

 offset=`ntpq -np | tail -1| cut -c 2- |awk '{print $1}' |xargs ntpdate -q 2>/dev/null |head -1 |awk -F, '{print $3}'|awk '{print $2}'`
 break
done
echo $offset


