import os
import re
import string
import time
from cam import openssl_wrap


def _parse_alt_names(s):
    if not s:
        return []
    if ',' in s:
        parts = s.split(',')
    else:
        parts = s.split()
    return [x.strip() for x in parts if x]


class Cert(object):

    def __init__(self, ca, name, config):
        self.name = name
        self.ca = ca
        self.cn = config['cn']
        self.ou = config.get('ou', '')
        self.days = config.get('days')

        self.alt_names = _parse_alt_names(config.get('alt_names'))
        if self.cn not in self.alt_names:
            self.alt_names.insert(0, self.cn)
        self.public_key_file = os.path.join(ca.basedir, 'public', 'certs', 
                                            '%s.pem' % name)
        self.private_key_file = os.path.join(ca.basedir, 'private',
                                             '%s.key' % name)

    def exists(self):
        return os.path.exists(self.public_key_file)

    def get_fingerprint(self, digest='sha1'):
        if self.exists():
            output = openssl_wrap.run('x509', '-in', self.public_key_file,
                                      '-noout', '-fingerprint', '-%s' % digest)
            m = re.search(r'=(.*)$', output)
            if m:
                return m.group(1)
        return None

    def get_expiration_date(self):
        if self.exists():
            output = openssl_wrap.run('x509', '-in', self.public_key_file,
                                      '-noout', '-dates')
            m = re.search(r'notAfter=(.*)', output)
            if m:
                return time.mktime(time.strptime(m.group(1),
                                                 '%b %d %H:%M:%S %Y %Z'))
        return None

    def expired(self):
        now = time.time()
        return self.get_expiration_date() > now

    
