#! /usr/bin/env python
"""Generate Bulk Certificates
__version__ = '0.1'
__author__ = 'Stuart Wilson'
Script to generate batch of certificates based on a request file as input:
"""

import pykeytool.pykeytool
import fileinput
import os
import logging
import argparse
import glob

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
logging.config.fileConfig(os.path.join(BASE_DIR, 'config', 'logging.ini'), disable_existing_loggers=False)
logger = logging.getLogger(__name__)

if __name__ == '__main__':

    parser = argparse.ArgumentParser(description='Generate Certificates using CSR files')

    parser.add_argument('-r', dest='requestfile', action='store', help='Request file located with csr files', required=True)
    parser.add_argument('-c', dest='context', action='store', help='Context to submit CSR against', required=True)


    args = parser.parse_args()
    # Identify the directory to load and write the certificates to.
    requestdir = os.path.dirname(os.path.abspath(args.requestfile))
    #Iterate over id's listed in file
    logger.info('########### Starting Batch certificate Process ###########')
    count = len(open(args.requestfile).readlines())
    f_input = fileinput.input(files=args.requestfile)
    for lineno, id in enumerate(f_input, 1):
        #Strip off newline chars
        id = id.strip()
        #Generate Certificates
        context = args.context
        logger.info('Generating Certificate for %s', id)
        pykeytool.pykeytool.generate_online_cert(id, context, requestdir)
        logger.info('Processed Request Number: %s out of %s', lineno, count)

    f_input.close()
    # Checking and Tar up the certs's
    if len(glob.glob1(requestdir, "*.crt")) == count:
        logger.info('Number of certificate files created matches the number of requests in request file: %s', count)
    logger.info('########### Finished Batch certificate Process ###########')
