#!/usr/bin/env python

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

"""
import logging
import os
import sys

from fss_utils import getTargetFSS
from cis.utils import readprop, write_props_to_file

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__))

COMPONENT_NAME = 'trustmanagement'
TM_GRPC_PORT = 'trustmanagement.grpc.port'
TM_GRPC_PORT_VALUE = '4000'

def doPatching(ctx):
    logger.info("TrustManagement patch to add grpc port being executed: %s", ctx)
    if not has_tm_property():
        logger.info("Adding TM property file with grpc port")
        update_tm_properties()
    else:
        logger.info("trustmanagement.grpc.port already present, no action taken")

def has_tm_property():
    tm_props_file = '%s/trustmanagement.properties' % get_config_dir()
    tm_grpc_port = readprop(tm_props_file, TM_GRPC_PORT)
    if tm_grpc_port is None:
        return False
    return True

def update_tm_properties():
    tm_props_file = '%s/trustmanagement.properties' % get_config_dir()
    prop = [(TM_GRPC_PORT, TM_GRPC_PORT_VALUE)]
    write_props_to_file(tm_props_file, prop, mode='a')

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

