#!/usr/bin/env python3

from charmhelpers.core import hookenv
from os.path import exists
from strongswan.openssl import create_root_cert
from strongswan.actions import action_get, action_fail
from strongswan.constants import (
	IPSEC_D_CACERTS,
	CA_CERT
)


def create():
	"""
	Juju action that creates a self signed Root CA, as well as a local cert
	""" 
	params = action_get()
	if params:
		if params.get("overwrite") or not exists(IPSEC_D_CACERTS + CA_CERT) :
			create_root_cert( 
				params.get("subject"),
				params.get("lifetime"),
				params.get("keysize")
			)
			hookenv.log("Root CA certificate created.", level=hookenv.INFO)
			hookenv.log("Written into standard /etc/ipsec.d/cacerts directory", level=hookenv.INFO)
			hookenv.log("Local certificate created and signed by the CA", level=hookenv.INFO)
			hookenv.log("Written into standard /etc/ipsec.d/certs directory", level=hookenv.INFO)
		else:
			action_fail("Root CA already exists. Pass overwrite=true to overwrite.")
	else:
		action_fail("No parameters were passed to this action.")


if __name__ == '__main__':
	create()