#!/usr/bin/env python3

from charmhelpers.core import hookenv
from strongswan.openssl import create_host_cert
from strongswan.actions import action_get, action_set, action_fail
from os import chown 
from pwd import getpwnam
from grp import getgrnam

def create():
	"""
	Creates a host/user certificate and archives it to /home/ubuntu
	"""
	params = action_get()
	if params:
		file_path = create_host_cert(
			params.get("subject"), 
			params.get("lifetime"),
			params.get("keysize"),
			params.get("out")
		)
		if file_path:
			chown( 
				file_path, 
				getpwnam('ubuntu').pw_uid, 
				getgrnam('ubuntu').gr_gid
			)
			action_set(outpath=file_path)
		else:
			action_fail("Out file must be either tar.gz, pkcs12 or gzip.")
	else:
		action_fail("No parameters passed to action create-host-certificate")



if __name__ == '__main__':
	create()
	