#!/usr/bin/python

# checks a set of standard OSG CRLs for validity

from __future__ import division

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

from os.path import expanduser

cert_hashes = ["ba240aa8"]

def try_home_install(c_hash):
    """
    Try to install the required certs into $HOME/.globus/certificates
    It might be too late for this glidein, but might help the following
    glideins
    """
    home_path = expanduser("~")
    if not os.path.exists(home_path + "/.globus/certificates"):
        os.makedirs(home_path + "/.globus/certificates")
    if not os.path.exists(home_path + "/.globus/certificates/" + c_hash + ".0"):
        print("Attempting install into " + home_path + "/.globus/certificates/")
        cmd = "cd " + home_path + "/.globus/certificates" + \
              " && wget -nv -O cacerts.tar.gz http://osg-flock.grid.iu.edu/cacerts.tar.gz" + \
              " && tar xzf cacerts.tar.gz" + \
              " && rm -f cacerts.tar.gz *.r0"
        subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0]


for c_hash in cert_hashes:
    home_path = expanduser("~")
    cert_path = "/etc/grid-security/certificates/" + c_hash + ".0"
    crl_path = "/etc/grid-security/certificates/" + c_hash + ".r0"
    if 'X509_CERT_DIR' in os.environ:
        cert_path = os.environ['X509_CERT_DIR'] + "/" + c_hash + ".0"
        crl_path = os.environ['X509_CERT_DIR'] + "/" + c_hash + ".r0"
    elif os.path.exists(home_path + "/.globus/certificates"):
        cert_path = home_path + "/.globus/certificates/" + c_hash + ".0"
        crl_path = home_path + "/.globus/certificates/" + c_hash + ".r0"

    print("Checking CA certificate " + cert_path)
    if not os.path.exists(cert_path):
        print("WARNING: Missing required CA certificate: %s" %(cert_path))
        #try_home_install(c_hash)
        sys.exit(0)

    if os.path.exists(crl_path):
        # be a little bit extra careful with error handling here - we only
        # want the test to fail if there is actually a CRL expiration and 
        # not if anything else fails
        diff = 0
        try:
            cmd = "openssl crl -in " + crl_path + " -nextupdate -noout"
            next_update = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0]
            next_update = next_update.strip()
            next_update = re.sub(".*=", "", next_update)
            print("Next update for CRL " + c_hash + ".r0 is " + next_update + \
                  " (full path: " + crl_path + ")")
            # example: Apr 22 17:00:00 2016 GMT
            dt = datetime.datetime.strptime(next_update, "%b %d %H:%M:%S %Y %Z")
            # epoch calculations in Python 2.6 makes me sad
            td = dt - datetime.datetime(1970,1,1)
            secs = (td.microseconds + (td.seconds + td.days * 86400) * 10**6) / 10**6 
            diff = time.time() - secs
        except:
            pass
        # make sure the CRL is valid for a while
        if diff > 1*60*60:
            print("WARNING: CRL is expired, or about to expire!")
            #try_home_install(c_hash)
            sys.exit(0)

sys.exit(0)

