#!/usr/bin/python
"""
The generator of extension certificate pair.
Usage:
    %s [-h] [--help] ([-k <extKey>]|[--key <extKey>]...) ([-t <outputTemplate>]|[--template <outputTemplate>]...)
    ([-c]|[--cleanup]...) [--pythonPath=...]

    -k <extKey> | --key <extKey>:
        The extension key which will be used later on to authenticate in front of the vpxd. The extension key
        will be persisted in  {outputTemplate}.ext file.

    -t <outputTemplate> | --template <outputTemplate>:
        Template of the output files. Using this template the extension key generator will persist the extension
        public key in {outputTemplate}.cert, extension private key in {outputTemplate}.key and VC extension key
        in {outputTemplate}.ext

    -c | --cleanup
        Cleaning up all created certificates by given template

    --pythonPath=<modules-paths>
        Additional modules which have to be added to the python path. The value
        is comma separated.

Exit status:
    0   If Ok
    2   If command cannot execute (e.g. because of missing or incorrect arguments)

Example:
    extensionKeyGenerator -k com.vmware.migrate-connector -t vpxd_connector
    extensionKeyGenerator -t vpxd_connector -c
"""

import sys
import os.path
import getopt
import platform
try:
    from OpenSSL import crypto
    isCryptoInstalled = True
except ImportError:
    isCryptoInstalled = False
import time
import logging
import uuid
import subprocess

EXIT_STATUS_OK = 0
EXIT_CERT_NOT_GENERATED = 1
EXIT_STATUS_ERROR = 2

logger = logging.getLogger(__name__)

def usage(argv):
    applName = os.path.basename(argv[0])
    print(__doc__ % applName)

def _setupLogging():
    ''' Setups logger. Path to `tools` package should be available already
    via sys.path !
    '''
    import logging_utils
    logging_utils.basicConfig(level=logging.DEBUG)

def createCertificatePair():
    '''Create a CA certificate and key for VMWare products. The certificates
    pair will be created with the VMWare information on them, hence everybody
    using them could check if they are created and intended to be used by
    VMWare products.

    @return: A certificate pair containing the generated certificate and its
    paired private key.
    '''
    RSA_KEY_SIZE = 2048
    CERT_NOT_BEFORE = -24 * 60 * 60
    CERT_NOT_AFTER = 31 * 24 * 60 * 60 #1 Month

    # create a key pair
    k = crypto.PKey()
    k.generate_key(crypto.TYPE_RSA, RSA_KEY_SIZE)
    # create a self-signed cert
    cert = crypto.X509()
    cert.get_subject().C = "US"
    cert.get_subject().ST = "California"
    cert.get_subject().L = "Palo Alto"
    cert.get_subject().O = "VMware, Inc."
    cert.get_subject().OU = "VMware, Inc."
    cert.set_serial_number(int(time.time() * 10000))
    cert.gmtime_adj_notBefore(CERT_NOT_BEFORE)
    cert.gmtime_adj_notAfter(CERT_NOT_AFTER)

    cert.set_issuer(cert.get_subject())

    cert.set_pubkey(k)
    cert.sign(k, 'sha256')

    return cert, k

def generateCertificatesWithCrypto(outputTemplate):
    ''' Creates certificate pair and stores it in given output template.
    The function uses pythonOpenSsl to generate the self-signed certificates.
    The function also persists the given extension key in {outputTemplate}.ext file.

    @param outputTemplate: Template of the output files. Using this template the extension key generator
    will persist the extension public key in {outputTemplate}.cert, extension private key in
    {outputTemplate}.key and VC extension key in {outputTemplate}.ext
    '''
    cert, key = createCertificatePair()

    #Store Public Key
    with open("%s.cert" % outputTemplate, "wb") as fp:
        fp.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
        logger.debug("Persists the public certificate in: %s.cert", outputTemplate)
    #Store Private Key
    with open("%s.key" % outputTemplate, "wb") as fp:
        fp.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, key))
        logger.debug("Persists the private key in: %s.key", outputTemplate)

    logger.info("The certificates were successfully generated.")
    return True

def generateCertificatesWithOpenssl(outputTemplate):
    ''' Creates certificate pair and stores it in given output template.
    The function uses /usr/lib/openssl to generate the self-signed certificates.
    The function also persists the given extension key in {outputTemplate}.ext file.

    @param outputTemplate: Template of the output files. Using this template the extension key generator
    will persist the extension public key in {outputTemplate}.cert, extension private key in
    {outputTemplate}.key and VC extension key in {outputTemplate}.ext
    '''
    osType = platform.system()
    if osType.lower() != 'linux':
        logger.error("Os %s is currently not supported", osType)
        return False

    opensslTool = '/usr/bin/openssl'
    data = {
        'hostName' : 'unknown-hostname',
        'curTime' : time.time(),
        'certUniqIdent' : uuid.uuid4(),
        'certMagicIdent' : '564d7761726520496e632e',
    }

    config = \
'''
[ req ]
default_bits            = 2048
distinguished_name      = req_distinguished_name
string_mask             = nombstr
#Don't encrypt the key
encrypt_key             = no
prompt                  = no

[ req_distinguished_name ]
countryName             = US
stateOrProvinceName     = California
localityName            = Palo Alto
0.organizationName      = VMware, Inc.
organizationalUnitName  = VMware, Inc.
emailAddress            = ssl-certificates@vmware.com
commonName              = %(hostName)s
unstructuredName        = %(curTime)s,%(certUniqIdent)s,%(certMagicIdent)s
''' % data

    # Store config file
    configFile = "cert.cnf"
    with open(configFile, 'w') as fp:
        fp.write(config)

    privateFile = "%s.key" % outputTemplate
    certFile = "%s.cert" % outputTemplate
    # Generates the self-signed certificates
    logger.info("Start generating celf-signed certificates...")
    subprocess.call([
        opensslTool,
                'req',
                '-x509',
                '-nodes',
                '-newkey', 'rsa:2048',
                '-config', configFile,
                '-keyout', privateFile,
                '-out', certFile,
                '-days', '31' # 1month
    ])

    os.remove(configFile)

    if os.path.exists(privateFile) and os.path.exists(certFile):
        logger.info('The certificates were successfully generated')
    else:
        logger.warn('Certificates generation were unsuccessful')
        return False

    return True

def removeFile(filePath):
    '''Removes a file without throwing exception if the file is not present.

    @param filePath: Path to the file
    '''
    try:
        os.remove(filePath)
    except OSError:
        pass

def cleanCertificates(template):
    '''Cleaning up all created certificates by given template

    @param template: Template of the generated certificates which need to be removed
    '''
    #Remove extension key
    removeFile("%s.ext" % template)

    #Remove public key
    removeFile("%s.cert" % template)

    #Remove private key
    removeFile("%s.key" % template)

def main(argv=sys.argv):

    extensionKey = None
    template = None
    cleanup = False

    # parse command line options
    try:
        opts, _args = getopt.getopt(argv[1:], "hck:t:", ["help", "cleanup", "key=",
            "template=", "pythonPath="])
    except getopt.error as msg:
        print(msg)
        print("for help use --help")
        sys.stderr.write("Error parsing arguments: %s\n", msg)
        return EXIT_STATUS_ERROR

    # process options
    for o, a in opts:
        if o in ("-h", "--help"):
            usage(argv)
            return EXIT_STATUS_OK
        if o in ("-k", "--key"):
            extensionKey = a
        if o in ("-t", "--template"):
            template = a
        if o in ("-c", "--cleanup"):
            cleanup = True
        if o in ["--pythonPath"]:
            for pythonpath in a.split(','):
                sys.path.append(pythonpath)

    _setupLogging()

    if not cleanup and extensionKey == None or template == None:
        usage(argv)
        return EXIT_STATUS_ERROR

    if cleanup:
        cleanCertificates(template)
    else:
        if isCryptoInstalled:
            succ = generateCertificatesWithCrypto(template)
        else:
            succ = generateCertificatesWithOpenssl(template)

        if not succ:
            return EXIT_CERT_NOT_GENERATED

        #Store Extension Key
        with open("%s.ext" % template, "w") as fp:
            fp.write(extensionKey)
            logger.debug("Persists the extension key in: %s.ext", template)

    return EXIT_STATUS_OK

if __name__ == "__main__":
    sys.exit(main())
