#!/usr/bin/env python
import os
import sys
import socket
import random
import yaml
from OpenSSL.crypto import *

if len(sys.argv) < 2:
    print('Usage: ajenti-ssl-gen <hostname> [-f]')
    sys.exit(1)

host = sys.argv[1]
etcdir = '/etc/ajenti'
certificate_path = '%s/ajenti.pem' % etcdir
config_path = '%s/config.yml' % etcdir

config = yaml.load(open(config_path))

if not config['ssl']['enable']:
    print 'SSL is not enabled in config.yml'
    sys.exit(2)

if len(sys.argv) == 2:
    if config['ssl']['certificate']:
        print(':: SSL is already configured')
        sys.exit(1)

key = PKey()
key.generate_key(TYPE_RSA, 4096)
cert = X509()
cert.get_subject().countryName = 'NA'
cert.get_subject().organizationName = socket.gethostname()
cert.get_subject().commonName = 'ajenti'
cert.set_pubkey(key)
cert.set_serial_number(random.getrandbits(8 * 20))
cert.gmtime_adj_notBefore(0)
cert.gmtime_adj_notAfter(10 * 365 * 24 * 60 * 60)
cert.set_issuer(cert.get_subject())
cert.sign(key, 'sha1')


with open(certificate_path, 'w') as f:
    f.write(dump_privatekey(FILETYPE_PEM, key))
    f.write(dump_certificate(FILETYPE_PEM, cert))
