#!/usr/bin/python
# This script generates a RSA keypair in the specified directory

import sys, argparse, os
from os.path import basename
from Crypto.PublicKey import RSA

def generate_RSA(bits=4096):
    private = RSA.generate(bits)
    public = private.publickey()
    return private, public

def __make_parser():
    p = argparse.ArgumentParser(description='This generates an rsa-keypair')
    p.add_argument('-b', '--basename', type=str, help='specify the keypairs base filename', default = None, required = False)
    p.add_argument('-d', '--output-directory', type=str, help='specify an alternate output directory for the decrypted file', default = None, required = False)
    return p

def __main(argv):
    parser = __make_parser()
    settings = parser.parse_args(argv[1:])
    MYDIR = os.path.dirname(os.path.realpath(__file__))

    if (not os.path.isdir(settings.output_directory)):
        sys.stderr.write('Error: directory \'' + settings.output_directory + '\' does not exist')
        sys.exit(1)

    out_private_keypath = os.path.join(settings.output_directory, settings.basename + '.pem')
    out_public_keypath = os.path.join(settings.output_directory, settings.basename + '.pub')

    if (os.path.isfile(out_private_keypath) or os.path.isfile(out_public_keypath)):
        sys.stderr.write('Error: key with name \'' + settings.basename + '\' already exists')
        sys.exit(2)

    private_key_pem, public_key_pem = generate_RSA()

    private_key_file = open(out_private_keypath, "w")
    print >>private_key_file, private_key_pem.exportKey()

    public_key_file = open(out_public_keypath, "w")
    print >>public_key_file, public_key_pem.exportKey()

    print out_private_keypath
    print out_public_keypath
    sys.exit(0)

if __name__ == "__main__":
    __main(sys.argv)

__doc__ += __make_parser().format_help()
