#!/usr/bin/python

import os

import time


def monitor(content):

        os.popen('curl -vv "http://alert.sae.sina.com.cn/new/?service=hardware_time&checkpoint=hardware_time_error&title=%s&content=%s&cluster=public&grade=2"'%(content,content))


if __name__ == '__main__':

        sys_time=time.time()

        host=os.popen('hostname').read().split('\n')[0]

        hardware_time=" ".join(os.popen('hwclock --show --utc').read().split(" ")[0:6])

        try:

                hwclock_timestamp = time.mktime(time.strptime(hardware_time, '%a %d %b %Y %I:%M:%S %p'))        

        except ValueError, e:

                monitor(host+'_unkown_clock_modules')

                sys.exit(0)

        difference_time=abs(int(sys_time)-int(hwclock_timestamp))

        if difference_time > 60:

                ntp_time_list=[]

                ntp_time=os.popen('ntpq -p').read()

                ntps=ntp_time.split('\n')[2].split()[-2]

                if abs(eval(ntps)) >= 1000:

                        print '+++'

                        monitor(host+'_ntp_time_difference_'+str(abs(eval(ntps))))

                else:

                        print '++++'

                        os.popen('hwclock --systohc')

                        monitor(host+'_hardware_'+str(difference_time)+'s')