#!/bin/bash
#
# (c) 2006,2007,2023 Instituto Superior Técnico
#
# License: GPL-2
#

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

function verbosemsg () {
    case $VERBOSE in 
	yes | YES)
	    echo $*
	    ;;
	*)
    esac
}

# Verifica se o relogio da maquina local esta certo ou nao.  Se o
# relogio da mauqina local estiver certo, e uma maquina remota tiver
# ntp então é possível verificar o relogio da maquina remota.

# $1 - Hostname para interrogar o relogio
function sync () {
    DRIFT=0`ntpdate -q -u $* | tail -1 | cut -d ' ' -f 10`
    #echo $DRIFT
    SYNC=`printf "scale = 20\ndefine abs ( n ) { if ( n > 0 ) return n else return -n }\nabs($DRIFT) < 4\n" | bc`
    if [ "$SYNC" = "1" ] ; then
	return 0
    else
	echo "Args $*"
	echo "DRIFT=$DRIFT SYNC=$SYNC"
	return 1
    fi
}

# Verifica se o relogio da maquina local está sincronizado ou não,
# utilizando o ntpdate-debian introduzindo com a Debian etch.

function sync-local () {
    T=`ntpdate-debian -q -u`
    if echo $T | grep -q offset ; then
        # Old ntpdate-debian
        DRIFT=0`tail -1 | sed "s/.*offset //" | cut -d ' ' -f 1`
    else
        # ntpdate-debian used by ntpsec
        DRIFT=0`echo $T | cut -d ' ' -f 4`
    fi
    #echo $DRIFT
    SYNC=`printf "scale = 20\ndefine abs ( n ) { if ( n > 0 ) return n else return -n }\nabs($DRIFT) < 4\n" | bc`
    if [ "$SYNC" = "1" ] ; then
	return 0
    else
	echo "DRIFT=$DRIFT SYNC=$SYNC"
	return 1
    fi
}

if test -f /etc/default/ntpsec-ntpdate ; then
    source /etc/default/ntpsec-ntpdate
else
    source /etc/default/ntpdate
fi

if [ "A$1" == "A-q" ] ; then
    VERBOSE=NO
    shift
else
    VERBOSE=YES
fi
if [ "A$1" == "A-v" ] ; then
    VERBOSE=YES
    shift
fi

#DRIFT=`ntpdate -q -u pool.ntp.org | tail -1 | cut -d ' ' -f 10`
#verbosemsg $DRIFT
#SYNC=`printf "scale = 20\ndefine abs ( n ) { if ( n > 0 ) return n else return -n }\nabs($DRIFT) < 10\n" | bc`

# Check local ntp server

if [ -x /usr/sbin/ntpdate-debian ] ; then
    if sync-local ; then
	verbosemsg "Clock $HOSTNAME synchronized, verified with ntpdate-debian command"
    else
	echo "Clock $HOSTNAME desynchronized, verified with ntpdate-debian command"
	exit
    fi
else
    if sync ${NTPSERVERS:-pool.ntp.org} ; then
	verbosemsg "Clock $HOSTNAME synchronized, verified using ${NTPSERVERS:-pool.ntp.org} command"
    else
	echo "Clock $HOSTNAME desynchronized, verified using ${NTPSERVERS:-pool.ntp.org} as reference"
	exit
    fi
fi

for name in $* ; do
    if sync $name ; then
	verbosemsg "Clock $name synchronized"
    else
	echo "Clock $name desynchronized"
    fi
done
