import urllib.request

import random
import sys
import os

from datetime import datetime
from datetime import timedelta

import dateutil.parser

import sys
def cprint(*text,color="blue",space=" ",end="\n"):
    #return 0 #disable print dbg
    if not color:
        print(text)
        return 0

    if color == "green":
        txt = '\033[92m'
    elif color == "red":
        txt = '\033[0;31m\033[1m'
    elif color == "yellow":
        txt = '\033[93m\033[1m'
    elif color == "cyan":
        txt = '\033[96m'
    else:
        txt = '\033[94m'
    for t in text:
        txt += str(t ) +" "
    #HEADER = '\033[95m'
    #OKBLUE = '\033[94m'
    #OKCYAN = '\033[96m'
    #OKGREEN = '\033[92m'
    #WARNING = '\033[93m'
    #FAIL = '\033[91m'
    #ENDC = '\033[0m'
    #BOLD = '\033[1m'
    #UNDERLINE = '\033[4m'
    txt += '\033[0m'
    print(txt,end=end)
    #return txt
    try:
        sys.stdout.flush() # to grep output
    except BrokenPipeError as e:
        print("BROKEN PIPE ERROR CPRINT = EXIT")
        #exit()


host = "http://uxsrv.de"
host = "http://librelight.de"
#host = "https://google.com"
host += "?r={}".format(random.randint(1_000_000_000,9_000_000_000))

print(sys.argv)

if "-v" in sys.argv:print(host)
if "-v" in sys.argv:print()

import ssl

#ignore cert warning ... localtime is not correct
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

now = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
now = dateutil.parser.parse(now)
now = now.replace(tzinfo=None)
try:
    with urllib.request.urlopen(host,context=ctx) as response:
       #print(dir(response) )
       date = response.getheader("date")
       if "-v" in sys.argv:print("response:".ljust(20," "),date)
       
       date = dateutil.parser.parse(date)
       
       date  = date.replace(tzinfo=None)
       delta = date-now
       if "-v" in sys.argv:print("delta:   ".ljust(20," "),delta,type(delta))
       
       #print( timedelta(seconds=100))
       max_delta=timedelta(seconds=100)
       min_delta=timedelta(seconds=-100)
       print("-------")
       print( delta > max_delta , delta < min_delta)
       if delta > min_delta and delta < max_delta:
           cprint(delta,"delta is OK",color="green")
           exit()


       cprint(delta,"delta is to high",color="red")

       if "-v" in sys.argv:print("parse:   ".ljust(20," "),date)
       date = date.strftime("%Y-%m-%d %H:%M:%S")

       ndate = os.popen("date").read().strip()
       print("current date: ".ljust(20," "),ndate)

       # set local linux date
       CMD = "/usr/bin/date -u -s '{}' > /dev/null ".format(date)
       print("CMD:".ljust(20," "),CMD)
       os.system(CMD)

       date = os.popen("date").read().strip()
       print("current date: ".ljust(20," "),date)

       # set hwclock
       date = os.popen("/usr/sbin/hwclock").read().strip()
       print("hwclock: ".ljust(20," "),date)
       date = os.popen("/usr/sbin/hwclock -w").read().strip()
       print("hwclock: ".ljust(20," "),date)
except Exception as e:
    cprint("ERR",e,color="red")