#!/usr/bin/python
VERSION = '0.1'
import os, sys
from getopt import getopt, GetoptError
import ConfigParser
from subprocess import call


def usage():
    print  '''
    Parameter:
    -f <privacyidea.ini file>
    -h : help
    '''


def create_keys(file):
    print "Creating audit signing keys..."
    config_file = os.path.basename(file)
    config_path = os.path.abspath(os.path.dirname(file))
    config = ConfigParser.ConfigParser()
    config.read(file)
    config.set("DEFAULT", "here", config_path)
    private = config.get('DEFAULT', "privacyideaAudit.key.private")
    public = config.get('DEFAULT', "privacyideaAudit.key.public")

    r = call("openssl genrsa -out %s 2048" % private, shell=True)
    if r == 0:
        print "create private key: %s" % private

    r = call("openssl rsa -in %s -pubout -out %s" % (private, public), shell=True)
    if r == 0:
        print "written public key: %s" % private



def main():

    file = ""
    try:
        opts, args = getopt(sys.argv[1:], "f:", ["file="])

    except GetoptError:
        print "There is an error in your parameter syntax:"
        usage()
        sys.exit(1)

    for opt, arg in opts:
        if opt in ('-f', '--file'):
            file = arg
        elif opt in ('-h', '--help'):
            usage()
            sys.exit(1)

    if file:
        create_keys(file)
    else:
        usage()
        sys.exit(2)

if __name__ == '__main__':
    main()
