import pycurl, time, sys
import datetime

def get_url_last_modified(url):
    try:
        c = pycurl.Curl()
        c.setopt(pycurl.URL, url)
        c.setopt(pycurl.CONNECTTIMEOUT, 5)
        c.setopt(pycurl.TIMEOUT, 30)
        c.setopt(pycurl.FOLLOWLOCATION, 1)
        c.setopt(pycurl.NOBODY, 1)
        c.setopt(pycurl.OPT_FILETIME, 1)
        c.perform()
        filetime = c.getinfo(pycurl.INFO_FILETIME)
        if filetime < 0:
            return None
        else:
            return filetime
    except:
        return None

def check_mirror_up_to_date(url):
    mint_timestamp = get_url_last_modified("http://packages.linuxmint.com/db/version")
    if mint_timestamp == None:
        print "OK - can't find Mint age"
        return True
    mint_date = datetime.datetime.fromtimestamp(mint_timestamp)
    now = datetime.datetime.now()

    mint_age = (now - mint_date).days
    if (mint_age < 2):
        # If Mint servers were updated recently, the age is irrelevant (it would measure the time between now and the last update)
        print "OK - Mint was modified less than 2 days ago, non-conclusive"
        return True

    mirror_timestamp = get_url_last_modified("%s/db/version" % url)
    if mirror_timestamp is None:
        print "ERROR - can't find mirror age!!"
        return False
    mirror_date = datetime.datetime.fromtimestamp(mirror_timestamp)
    mirror_age = (mint_date - mirror_date).days
    if (mirror_age > 2):
        print "Mirror is out of date by %d days!" % mirror_age
        return False
    else:
        print "OK"
        return True

check_mirror_up_to_date(sys.argv[1])
