#!/usr/bin/env python

#
# Copyright 2017 VMware, Inc.  All rights reserved. -- VMware Confidential
#
"""
Patch script that does the following:
Updates the privileges for Certificate Management

"""
import logging
import os
import re
import sys
import warnings

vmware_python_path = os.getenv('VMWARE_PYTHON_PATH')
if vmware_python_path and os.path.exists(vmware_python_path):
    sys.path.append(vmware_python_path)

from cis.cisreglib import AuthzClient, CisregOptionParser, \
    LookupServiceClient, SsoClient, VmafdClient, _get_syscfg_info
from cis.vecs import SsoGroup, vmafd_machine_id
from cis.utils import get_deployment_nodetype

logger = logging.getLogger(__name__)
sys.path.append('/usr/lib/vmware-vmafd/lib64')

# Suppress warnings coming from vmafd and identity imports.
with warnings.catch_warnings():
    warnings.simplefilter('ignore', RuntimeWarning)
    import vmafdpy3
    from identity.vmkeystore import VmKeyStore

sys.path.append(os.path.dirname(__file__))
# import utils
AUTHZ_TYPE_ID = 'cs.authorization'
EP_AUTHZ_PROTOCOL = 'vmomi'
EP_AUTHZ_TYPE_ID = 'com.vmware.cis.authorization.server'
MACHINE_NAME = 'machine'
# PATCH_VERSION = '2'
COMPONENT_NAME = 'certificatemanagement'

def isInfraNode():
    try:
        node_type = get_deployment_nodetype()
        logger.info('Node type is %s' % node_type)
        return node_type == 'infrastructure'
    except Exception as e:
        logger.warning('Failed to get_deployment_nodetype: %s' % str(e))
        return False

def doPatching(ctx):
    logger.info("CertificateManagement patch: being executed %s", ctx)

    # skip Authz on infra node
    if isInfraNode():
        return

    logger.info("Updating privileges.")
    update_privs()


def get_config_dir():
    return '/usr/lib/vmware-%s/config' % COMPONENT_NAME


def update_privs():

    logger.info("Connecting to Lookup Service")
    ls_url, domain_name = _get_syscfg_info()
    ls_obj = LookupServiceClient(ls_url, retry_count=1)
    logger.info("Getting STS endpoint")
    sts_url, sts_cert_data = ls_obj.get_sts_endpoint_data()

    logger.info("Logging into SSO AdminClient as machine solution user")
    cert = None
    key = None

    with VmKeyStore('VKS') as ks:
        ks.load(MACHINE_NAME)
        cert = ks.get_certificate(MACHINE_NAME)
        key = ks.get_key(MACHINE_NAME)

    sso_client = SsoClient(sts_url, sts_cert_data, None, None, cert=cert,
                               key=key)
    ls_obj.set_sso_client(sso_client)
    authz_endpoints = ls_obj.get_service_endpoints(
                       AUTHZ_TYPE_ID, ep_protocol=EP_AUTHZ_PROTOCOL,
                       ep_type=EP_AUTHZ_TYPE_ID, local_nodeid=None)

    cert_mgmt_privs_xml_file = '%s/privileges.xml' % get_config_dir()

    cisreg_options = {'permission.newPrivilege': cert_mgmt_privs_xml_file}

    cisreg_optparser = CisregOptionParser(cisreg_options)
    logger.info("Logging into Authz")
    authz_client = AuthzClient(authz_endpoints[0].url, sso_client)
    logger.info("Updating global permissions certificate management")
    authz_client.load_privs(cisreg_optparser.get_privs())
