#!/usr/bin/python

import base64
import errno
import fcntl
import hashlib
import ldap
import os
import subprocess
import sys
import textwrap
from OpenSSL import crypto, SSL

CERTS_DIR = '/var/lib/scripts-certs'

ll = ldap.initialize('ldapi://%2fvar%2frun%2fslapd-scripts.socket/')
with open('/etc/signup-ldap-pw') as pw_file:
    ll.simple_bind_s("cn=Directory Manager", pw_file.read())

if not os.path.exists(CERTS_DIR):
    os.mkdir(CERTS_DIR)

vhosts = ll.search_s(
    'ou=VirtualHosts,dc=scripts,dc=mit,dc=edu',
    ldap.SCOPE_SUBTREE,
    '(&(objectClass=scriptsVhost)(scriptsVhostCertificate=*))',
    ['scriptsVhostName', 'scriptsVhostAlias', 'scriptsVhostCertificate', 'scriptsVhostCertificateKeyFile'])

vhosts.sort(key=lambda (dn, vhost): vhost['scriptsVhostName'])

cert_filenames = set()
error = False

def err(e):
    global error
    sys.stderr.write(e)
    error = True

def conf(vhost):
    name, = vhost['scriptsVhostName']
    aliases = vhost.get('scriptsVhostAlias', [])
    certs, = vhost['scriptsVhostCertificate']
    try:
        key_filename, = vhost['scriptsVhostCertificateKeyFile']
    except KeyError:
        err('Error: missing scriptsVhostCertificateKeyFile for vhost {}\n'.format(name))
        return

    try:
        certs = [crypto.load_certificate(crypto.FILETYPE_ASN1, base64.b64decode(cert)) for cert in certs.split()]
    except (TypeError, crypto.Error) as e:
        err('Error: malformed certificate list for vhost {}: {}\n'.format(name, e))
        return

    if not certs:
        err('Error: empty certificate list for vhost {}\n'.format(name))
        return

    key_path = os.path.join('/etc/pki/tls/private', key_filename)
    if os.path.split(os.path.abspath(key_path)) != ('/etc/pki/tls/private', key_filename):
        err('Error: bad key filename {} for vhost {}\n'.format(key_path, name))
        return

    ctx = SSL.Context(SSL.SSLv23_METHOD)
    try:
        ctx.use_privatekey_file(key_path, crypto.FILETYPE_PEM)
    except (SSL.Error, crypto.Error) as e:
        err('Error: could not read key {} for vhost {}: {}\n'.format(key_path, name, e))
        return

    ctx.use_certificate(certs[0])
    for cert in certs[1:]:
        ctx.add_extra_chain_cert(cert)

    try:
        ctx.check_privatekey()
    except SSL.Error as e:
        err('Error: key {} does not match certificate for vhost {}: {}\n'.format(key_path, name, e))
        return

    certs_pem = ''.join(crypto.dump_certificate(crypto.FILETYPE_PEM, cert) for cert in certs)
    cert_filename = base64.urlsafe_b64encode(hashlib.sha256(certs_pem).digest()).strip() + '.pem'
    cert_filenames.add(cert_filename)
    cert_path = os.path.join(CERTS_DIR, cert_filename)
    if not os.path.exists(cert_path):
        with open(cert_path + '.new', 'w') as cert_file:
            cert_file.write(certs_pem)
        os.rename(cert_path + '.new', cert_path)

    for port in 443, 444:
        yield '<VirtualHost *:{}>\n'.format(port)
        yield '\tServerName {}\n'.format(name)
        if aliases:
            yield '\tServerAlias {}\n'.format(' '.join(aliases))
        yield '\tInclude conf.d/vhost_ldap.conf\n'
        yield '\tInclude conf.d/vhosts-common-ssl.conf\n'
        if port == 444:
            yield '\tInclude conf.d/vhosts-common-ssl-cert.conf\n'
        yield '\tSSLCertificateFile {}\n'.format(cert_path)
        yield '\tSSLCertificateKeyFile {}\n'.format(key_path)
        yield '</VirtualHost>\n'

with open(os.path.join(CERTS_DIR, '.lock'), 'w') as lock_file:
    fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)

    new_vhosts_conf = \
        '# Generated by {}.  Manual changes will be lost.\n\n'.format(os.path.realpath(__file__)) + \
        ''.join(l for dn, vhost in vhosts for l in conf(vhost))

    try:
        with open(os.path.join(CERTS_DIR, 'vhosts.conf')) as vhosts_file:
            old_vhosts_conf = vhosts_file.read()
    except IOError as e:
        if e.errno == errno.ENOENT:
            old_vhosts_conf = None
        else:
            raise

    if old_vhosts_conf is not None and new_vhosts_conf != old_vhosts_conf:
        with open(os.path.join(CERTS_DIR, 'vhosts.conf.new'), 'w') as new_vhosts_file:
            new_vhosts_file.write(new_vhosts_conf)
        os.rename(os.path.join(CERTS_DIR, 'vhosts.conf.new'), os.path.join(CERTS_DIR, 'vhosts.conf'))

        configtest = subprocess.Popen(['apachectl', 'configtest'], stderr=subprocess.PIPE)
        e = configtest.communicate()[1]
        if configtest.returncode == 0 and e == 'Syntax OK\n':
            subprocess.check_call(['apachectl', 'graceful'])
        else:
            err('apachectl configtest failed:\n' + e)

    for filename in os.listdir(CERTS_DIR):
        if filename.endswith('.pem') and filename not in cert_filenames:
            os.remove(os.path.join(CERTS_DIR, filename))

    fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)

sys.exit(1 if error else 0)
