#!/usr/bin/python

# make sure the local clock is at least close to the correct time

from __future__ import division

import os
import sys
import subprocess
import re
import datetime
import time

try:
    import urllib.request as urllib
except ImportError:
    import urllib

# what is the difference we are willing to accept?
minutes_diff_ok = 5

# in minutes
my_ts = int(time.time()) / 60

# try to get the remote time - if this fails, we will exit cleanly
try:
    f = urllib.urlopen('http://osg-vo.isi.edu/osg/ticktock.php')
    remote_ts = int(f.read()) / 60
except Exception as e:
    print(e)
    sys.exit(0)

diff = my_ts - remote_ts
if abs(diff) < minutes_diff_ok:
    print("Clocks are synchronized")
elif my_ts > remote_ts:
    print("ERROR: My clock is ahead %d minutes" %(abs(diff)))
    sys.exit(1)
else:
    print("ERROR: My clock is behind %d minutes" %(abs(diff)))
    sys.exit(1)

sys.exit(0)

