# -----------------------------------------------------------------------------
# Connect to a particular process and add a new certificate to the 
# certificate store
# -----------------------------------------------------------------------------
import os
import sys
import vutil
from java.io import File, FileInputStream
from java.security.cert import CertificateFactory
from addCert import CertStoreUtil 
from com.vordel.archive.fed import DeploymentArchive
from archiveutil import DeploymentArchiveAPI
from com.vordel.es.util import ShorthandKeyFinder
from com.vordel.es.xes import PortableESPKFactory

certFileName = "ca.cer"
alias = "ca certificate"


# Gets the entity store from  archive file
fedFile = os.path.join(vutil.getVDISTDIR(), 'samples', 'scripts', 'fed', 'file.fed')
archive = DeploymentArchiveAPI(DeploymentArchive(fedFile))
esapi = archive.getEntityStoreAPI()
shkf = ShorthandKeyFinder(esapi.es)

# Gets the Cert Store using the short hand key
certStore = shkf.getEntity('/[Certificates]name=Certificate Store');

# Loads the certificate from a file 
cf = CertificateFactory.getInstance("X.509");
f =  File(certFileName)
cert = cf.generateCertificate(FileInputStream(f))

# Adds the Cert to the Cert Store
CertStoreUtil.addCertToStore(esapi, alias, cert)

# Update deployment archive
archive.deploymentArchive.updateConfiguration(esapi.es)
archive.deploymentArchive.writeToArchiveFile(fedFile)