#!/usr/bin/env python

#
# Copyright 2019 VMware, Inc.  All rights reserved. -- VMware Confidential
#
"""
Patch script that does the following:
Adds certificatemanagement.grpc.port to certificatemanagement.properties file, if not present

"""
import logging
import os
import sys
from cis.utils import readprop, write_props_to_file
from fss_utils import getTargetFSS

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)

logger = logging.getLogger(__name__)

sys.path.append(os.path.dirname(__file__))

PATCH_VERSION = '6'
COMPONENT_NAME = 'certificatemanagement'
CERTMGMT_GRPC_PORT = 'certificatemanagement.grpc.port'
CERTMGMT_GRPC_PORT_VALUE = '4002'

def doPatching(ctx):
    if getTargetFSS("HybridVC_SyncaaS"):
        logger.info("certificateManagement patch: being executed %s", ctx)
        if not has_certmgmt_property():
            logger.info("Adding gRPC port to certificatemanagement.properties file")
            update_certmgmt_properties()

def has_certmgmt_property():
    certmgmt_props_file = '%s/certificatemanagement.properties' % get_config_dir()
    certmgmt_props_version = readprop(certmgmt_props_file, CERTMGMT_GRPC_PORT)
    if certmgmt_props_version is None:
        return False
    return True

def update_certmgmt_properties():
    certmgmt_props_file = '%s/certificatemanagement.properties' % get_config_dir()
    prop = [(CERTMGMT_GRPC_PORT, CERTMGMT_GRPC_PORT_VALUE)]
    write_props_to_file(certmgmt_props_file, prop, mode='a')

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

