#!/usr/bin/env python

"""
Generate client and server CURVE certificate files then move them into the
appropriate store directory, private_keys or public_keys. The certificates
generated by this script are used by the stonehouse and ironhouse examples.
In practice this would be done by hand or some out-of-band process.
Author: Chris Laws
"""

import os
import shutil
import zmq.auth
import argparse
import uuid


def generate_certificates(base_dir, users, overwrite):
    ''' Generate client and server CURVE certificate files'''
    keys_dir = os.path.join(base_dir, 'certificates')
    public_keys_dir = os.path.join(base_dir, 'public_keys')
    secret_keys_dir = os.path.join(base_dir, 'private_keys')

    # Create directories for certificates, remove old content if necessary
    for d in [keys_dir, public_keys_dir, secret_keys_dir]:
        if os.path.exists(d):
            if overwrite:
                shutil.rmtree(d)
                os.mkdir(d)
        else:
            os.mkdir(d)

    client_id = str(uuid.uuid4())

    if users == 'all':
        # create new keys in certificates dir
        server_public_file, server_secret_file = zmq.auth.create_certificates(
            keys_dir, "server"
        )
        client_public_file, client_secret_file = zmq.auth.create_certificates(
            keys_dir, client_id
        )
    elif users == 'client':
        client_public_file, client_secret_file = zmq.auth.create_certificates(
            keys_dir, client_id
        )
    elif users == 'server':
        server_public_file, server_secret_file = zmq.auth.create_certificates(
            keys_dir, "server"
        )

    # move public keys to appropriate directory
    for key_file in os.listdir(keys_dir):
        if key_file.endswith(".key"):
            shutil.move(
                os.path.join(keys_dir, key_file), os.path.join(public_keys_dir, '.')
            )

    # move secret keys to appropriate directory
    for key_file in os.listdir(keys_dir):
        if key_file.endswith(".key_secret"):
            shutil.move(
                os.path.join(keys_dir, key_file), os.path.join(secret_keys_dir, '.')
            )


if __name__ == '__main__':

    parser = argparse.ArgumentParser()

    parser.add_argument('--path', required=True, help="path where the keys are generated", type=str)
    parser.add_argument('--users', nargs='?', help="generate for users: all, client or server. Defaults is client", type=str, const=1, default='client')
    parser.add_argument('--overwrite', nargs='?', help="overwrite existing. default is False", type=bool, const=1, default=False)

    args = parser.parse_args()
    path = args.path
    users = args.users
    overwrite = args.overwrite

    print(f'creating new certificates in {args.path}')

    if zmq.zmq_version_info() < (4, 0):
        raise RuntimeError(
            "Security is not supported in libzmq version < 4.0. libzmq version {0}".format(
                zmq.zmq_version()
            )
        )

    generate_certificates(path, users, overwrite)
