import errno
import fcntl
import logging
import re
import os
import getpass
import random
import shutil
import tempfile
import time
from cam import openssl_wrap
from cam import utils

log = logging.getLogger(__name__)


class _CAFiles(object):

    def __init__(self, basedir, **attrs):
        for key, value in attrs.items():
            setattr(self, key, os.path.join(basedir, value))


class CA(object):

    def __init__(self, basedir, config, password=None):
        self._pw = password
        self.basedir = basedir
        self.config = {'basedir': basedir, 'default_days': '365', 'ou': 'CA',
                       'days': '3650', 'country': 'XX', 'crl_url': '',
                       'signature_algorithm': 'sha256', 'bits': '2048'}
        self.config.update(config)
        self.files = _CAFiles(basedir, 
                              conf='conf/ca.conf',
                              public_key='public/ca.pem',
                              private_key='private/ca.key',
                              crl='public/ca.crl',
                              serial='serial',
                              crlnumber='crlnumber',
                              index='index')
        self._lock()

    def _getpw(self):
        if self._pw is None:
            self._pw = getpass.getpass(prompt='CA Password: ')
        return self._pw

    def _lock(self):
        self._lockfd = open(os.path.join(self.basedir, '_lock'), 'w+')
        n = 3
        while True:
            try:
                fcntl.lockf(self._lockfd, fcntl.LOCK_EX | fcntl.LOCK_NB)
                break
            except IOError, e:
                if e.errno in (errno.EACCES, errno.EAGAIN):
                    n -= 1
                    if n == 0:
                        log.error('another instance is running')
                        raise
                    time.sleep(1)
                    continue
                raise

    def _unlock(self):
        fcntl.lockf(self._lockfd, fcntl.LOCK_UN)
        self._lockfd.close()

    def _update_config(self):
        # Create the OpenSSL configuration file.
        utils.render(self.files.conf, 'openssl_config', self.config)

    def close(self):
        self._unlock()

    def create(self):
        old_umask = os.umask(077)

        for pathext in ('', 'conf', 'public', 'public/certs',
                        'public/crl', 'private', 'newcerts'):
            fullpath = os.path.join(self.basedir, pathext)
            if not os.path.isdir(fullpath):
                os.mkdir(fullpath)

        if not os.path.exists(self.files.index):
            log.info('creating new index file')
            open(self.files.index, 'w').close()

        if not os.path.exists(self.files.serial):
            serial = random.randint(1, 1000000000)
            log.info('initializing serial number (%d)', serial)
            with open(self.files.serial, 'w') as fd:
                fd.write('%08X\n' % serial)

        if not os.path.exists(self.files.crlnumber):
            with open(self.files.crlnumber, 'w') as fd:
                fd.write('01\n')

        self._update_config()

        # Generate keys if they do not exist.
        if not os.path.exists(self.files.public_key):
            tmpdir = tempfile.mkdtemp()
            csr_file = os.path.join(tmpdir, 'ca.csr')
            log.info('creating new RSA CA CSR')
            openssl_wrap.run_with_config(
                self.basedir, self.files.conf,
                'req', '-new',
                '-passout', 'pass:%s' % self._getpw(),
                '-keyout', self.files.private_key, '-out', csr_file)
            log.info('self-signing RSA CA certificate')
            openssl_wrap.run_with_config(
                self.basedir, self.files.conf,
                'ca', '-keyfile', self.files.private_key,
                '-key', self._getpw(),
                '-md', self.config['signature_algorithm'],
                '-extensions', 'v3_ca', '-out', self.files.public_key,
                '-days', self.config.get('days', self.config['default_days']),
                '-selfsign', '-infiles', csr_file)
            shutil.rmtree(tmpdir)

        os.umask(old_umask)

        # Make some files public.
        for path in (os.path.join(self.basedir, 'public'),
                     os.path.join(self.basedir, 'public/certs'),
                     self.files.public_key):
            if os.path.isdir(path):
                os.chmod(path, 0755)
            else:
                os.chmod(path, 0644)

    def gencrl(self):
        log.info('generating CRL')

        self._update_config()

        # Write the CRL in PEM format to a temporary file.
        tmpf = self.files.crl + '.tmp'
        openssl_wrap.run_with_config(
            self.basedir, self.files.conf,
            'ca', '-gencrl', '-out', tmpf,
            '-key', self._getpw())
        # Convert to DER format for distribution.
        openssl_wrap.run(
            'crl', '-inform', 'PEM', '-outform', 'DER',
            '-in', tmpf, '-out', self.files.crl)
        os.remove(tmpf)
        os.chmod(self.files.crl, 0644)

    def revoke(self, cert):
        log.info('revoking certificate %s', cert.name)
        openssl_wrap.run_with_config(
            self.basedir, self.files.conf,
            'ca', '-revoke', cert.public_key_file,
            '-key', self._getpw())
        self.gencrl()

    def verify(self, path):
        log.info('verifying certificate %s', path)
        args = ['verify', '-CAfile', self.files.public_key, path]
        try:
            openssl_wrap.run(*args, CAROOT=os.path.abspath(self.basedir))
        except openssl_wrap.CommandError:
            return False
        return True

    def generate(self, cert):
        self._update_config()

        expiry = cert.get_expiration_date()
        if expiry and expiry > time.time():
            log.warn('certificate is still valid')

        if cert.exists():
            log.warn('revoking previous version')
            self.revoke(cert)

        log.info('generating new certificate %s', cert.name)
        tmpdir = tempfile.mkdtemp()
        try:
            csr_file = os.path.join(tmpdir, '%s.csr' % cert.name)
            conf_file = os.path.join(tmpdir, '%s.conf' % cert.name)
            ext_file = os.path.join(tmpdir, '%s-ext.conf' % cert.name)
            conf = {'usage': 'client, server'}
            conf.update(self.config)
            conf['cn'] = cert.cn
            conf['days'] = cert.days or self.config['default_days']
            if cert.ou:
                conf['ou'] = cert.ou
            conf['alt_names'] = ''.join(
                ['DNS.%d=%s\n' % (idx + 1, x) 
                 for idx, x in enumerate(cert.alt_names)])
            utils.render(conf_file, 'openssl_config', conf)
            utils.render(ext_file, 'ext_config', conf)
            openssl_wrap.run_with_config(
                self.basedir, conf_file,
                'req', '-new', '-keyout', cert.private_key_file,
                '-' + self.config['signature_algorithm'],
                '-nodes', '-out', csr_file)
            os.chmod(cert.private_key_file, 0600)
            openssl_wrap.run_with_config(
                self.basedir, conf_file,
                'ca', '-days', conf['days'],
                '-key', self._getpw(),
                '-md', self.config['signature_algorithm'],
                '-policy', 'policy_anything', '-out', cert.public_key_file,
                '-extfile', ext_file, '-infiles', csr_file)
        finally:
            shutil.rmtree(tmpdir)

