#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#    LinOTP - the open source solution for two factor authentication
#    Copyright (C) 2010 - 2014 LSE Leading Security Experts GmbH
#
#    This file is part of LinOTP server.
#
#    This program is free software: you can redistribute it and/or
#    modify it under the terms of the GNU Affero General Public
#    License, version 3, as published by the Free Software Foundation.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the
#               GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
#
#    E-mail: linotp@lsexperts.de
#    Contact: www.linotp.org
#    Support: www.lsexperts.de
#

VERSION = '0.1'
import os, sys
from getopt import getopt, GetoptError
import ConfigParser
from subprocess import call

CONFIG_FILE = "/etc/apache2/sites-available/linotp2"

def usage():
    print  '''
    Parameter:
    -f <apache config file> (Default: %s)
    -h : help
    ''' % CONFIG_FILE


def create_keys(file):
	print "Creating certificate..."
	'''
	Read
    SSLCertificateFile    /etc/ssl/certs/linotpserver.pem
    SSLCertificateKeyFile /etc/ssl/private/linotpserver.key
	'''
	key = None
	cert = None
	f = 	open(file, 'r')
	for l in f:
		if l.strip()[:18] == "SSLCertificateFile":
			cert = l.split()[1]
		elif l.strip()[:21] == "SSLCertificateKeyFile":
			key = l.split()[1]
	f.close()

	if key and cert:
		command = "openssl req -x509 -newkey rsa:2048 -keyout %s -out %s -days 1000 -subj /CN=linotpserver -nodes" % (key, cert)
		r = call(command, shell=True)
		if r == 0:
			print "created key and cert..."
			os.chmod(key, 0x400)
		else:
			print "Failed to create key and cert: %i" % r
			sys.exit(r)

	else:
		print "Could not find key and cert!"
		print "key: %s" % key
		print "cert: %s" % cert
		sys.exit(2)


def main():

    file = CONFIG_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()
