#!/usr/bin/python

from __future__ import print_function

import ConfigParser
import base64
import os
import sys

from jwcrypto.common import json_decode

from ipalib import constants
from ipaplatform.paths import paths
from ipapython.secrets.client import CustodiaClient

conf = ConfigParser.ConfigParser()
conf.read(paths.IPA_DEFAULT_CONF)
hostname = conf.get('global', 'host')
realm = conf.get('global', 'realm')

keyname = "ca_wrapped/" + sys.argv[1]
servername = sys.argv[2]

service = constants.PKI_GSSAPI_SERVICE_NAME
client_keyfile = os.path.join(paths.PKI_TOMCAT, service + '.keys')
client_keytab = os.path.join(paths.PKI_TOMCAT, service + '.keytab')

client = CustodiaClient(
    client=hostname, server=servername, realm=realm,
    ldap_uri="ldaps://" + hostname,
    client_servicename=service,
    keyfile=client_keyfile, keytab=client_keytab,
    )

result_json = client.fetch_key(keyname, store=False)
result = json_decode(result_json)
certificate = result["certificate"]
wrapped_key = base64.b64decode(result["wrapped_key"])

# Custodia returns a PEM-encoded certificate and a base64-encoded
# DER PKIArchiveOptions object.  Output these values, separated by a
# null byte (certificate first), to be read by the Java
# IPACustodiaKeyRetriever that invoked this program.

print(certificate, wrapped_key, sep='\0', end='')
