#!/usr/bin/python

import sys
import re
import datetime
import email
import urllib.request

YEARS=365.25
# Huge values, for testing with https://www.bortzmeyer.org/apps/limit only.
DEPRECATION_THRESHOLD=datetime.timedelta(days=20*YEARS)
SUNSET_THRESHOLD=datetime.timedelta(days=70*YEARS)

def get(url):
    response =  urllib.request.urlopen(url) # May raise urllib.error.HTTPError or urllib.error.URLError
    now = datetime.datetime.now(datetime.UTC)
    deprecation = None
    sunset = None
    # RFC 9745
    if "deprecation" in response.headers:
        deprecation_text = response.headers["deprecation"]
        value = re.search("^@([0-9]+)$", deprecation_text)
        if value is None:
            raise Exception("Invalid Deprecation field in header: %s" % \
                            deprecation_text)
        deprecation = datetime.datetime.fromtimestamp(int(value.group(1)),
                                                      datetime.UTC)
    # RFC 8594
    if "sunset" in response.headers:
        sunset_text = response.headers["sunset"]
        sunset = email.utils.parsedate_to_datetime(sunset_text) # May raise ValueError
    if sunset is not None and deprecation is not None:
        if sunset < deprecation:
            raise Exception("Sunset is before Deprecation")
    if sunset is not None and (sunset - now) < SUNSET_THRESHOLD:     
        print("Only %s remaining before sunset" % \
              (sunset - now))
    elif deprecation is not None and (deprecation - now) < DEPRECATION_THRESHOLD:
        print("Only %s remaining before deprecation" % \
              (deprecation - now))
    # Else do nothing
    
for url in sys.argv[1:]:
    get(url)
    
