#!/bin/bash

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

NOW=$(date +%s)
INTERVAL=$[ 8 * 60 * 60 ]  # 8 hs
CONTROL=/tmp/.lastSyncTime

sync_time() {
    ntpdate-debian -s  || exit 1
    hwclock --systohc  || exit 1
    touch ${CONTROL}
}

[ ! -f ${CONTROL} ] && sync_time && exit 0

SYNCRONIZED=$(stat -c %Y ${CONTROL})
SECONDS=$[ ${NOW} - ${SYNCRONIZED} ]

[ ${SECONDS} -gt ${INTERVAL} ] && sync_time && exit 0
[ ${SECONDS} -lt 0           ] && sync_time && exit 0

exit 0
