#! /usr/bin/env python
"""Generate Bulk PKCS12
__version__ = '0.1'
__author__ = 'Stuart Wilson'
Script to generate batch of pkcs12 files 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__)))

# Set Logging to file - logs/pykeytool.log:
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 Keys and CSRs')

    parser.add_argument('-pkcs12pw', dest='pkcs12password', action='store', required=True,
                        help='Password used to protect PKCS12 files')

    parser.add_argument('-r', dest='requestfile', action='store', help='Request file to be processed', required=True)

    args = parser.parse_args()
    # Identify the directory to write the output to.
    requestdir = os.path.dirname(os.path.abspath(args.requestfile))
    logger.info('########### Starting Batch PKCS12 Update Process ###########')
    #Iterate over id's listed in file
    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()
        logger.info('Generating PKCS12 for %s', id)
        pykeytool.pykeytool.update_offline_pkcs12(id, requestdir, args.pkcs12password)
        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, "*.p12")) == count:
        logger.info('Number of PKCS12 files created matches the number of requests in request file: %s', count)
    logger.info('########### Finish Batch PKCS12 Update Process ###########')
