# -----------------------------------------------------------------------------
# Connect to a particular process and add a new certificate and key from 
# P12 file to the certificate store
# -----------------------------------------------------------------------------
import os
import sys
import vutil
from java.io import File
from java.lang import Integer
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

p12File = "certificate.p12"
p12Password = "test"
alias = "my 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 its short hand key
certStore = shkf.getEntity('/[Certificates]name=Certificate Store');

# Loads the private key from a file
f =  File(p12File)
privateKey = CertStoreUtil.getKeyFromP12(f, p12Password)

# Loads the certificates from the P12 file
cert = CertStoreUtil.getCertFromP12(f, p12Password)

# Adds the certificate and key to the Cert store
CertStoreUtil.addCertToStore(esapi, alias, cert, privateKey)

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

