#!/usr/bin/python

import base64
import hashlib
import ldap
import os
import sys
import textwrap

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 conf(vhost):
    name, = vhost['scriptsVhostName']
    aliases = vhost.get('scriptsVhostAlias', [])
    certs, = vhost['scriptsVhostCertificate']
    key_filename, = vhost['scriptsVhostCertificateKeyFile']

    certs = ''.join('-----BEGIN CERTIFICATE-----\n' + '\n'.join(textwrap.wrap(cert, 64)) + '\n-----END CERTIFICATE-----\n' for cert in certs.split())
    cert_filename = base64.urlsafe_b64encode(hashlib.sha256(certs).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)
        os.rename(cert_path + '.new', cert_path)

    key_path = os.path.join('/etc/pki/tls/private', key_filename)
    if not os.path.exists(key_path):
        sys.stderr.write("Error: key file {} does not exist for vhost {}\n".format(key_path, name))
        global error
        error = True
        return

    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, 'vhosts.conf.new'), 'w') as vhosts_file:
    vhosts_file.write('# Generated by {}.  Manual changes will be lost.\n\n'.format(os.path.realpath(__file__)))
    vhosts_file.write(''.join(l for dn, vhost in vhosts for l in conf(vhost)))
os.rename(os.path.join(CERTS_DIR, 'vhosts.conf.new'), os.path.join(CERTS_DIR, 'vhosts.conf'))

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))

sys.exit(1 if error else 0)
