#!/usr/bin/env python

#
# Copyright 2021 VMware, Inc.  All rights reserved. -- VMware Confidential
#
'''
This file provides the hooks which will be invoked during patching process.
'''
import logging
import sys
import os
import shutil
from pathlib import Path

sys.path.append(os.environ['VMWARE_PYTHON_PATH'])

import utils
import os
from cis.defaults import get_component_home_dir

logger = logging.getLogger(__name__)

COMPONENT = 'perfcharts'
PATCH_VERSION = '4'

perfcharts_config_file_path = "/etc/vmware-perfcharts/log4j.properties"
perfcharts_config_file_path_suffix = "/etc/vmware-perfcharts/log4j.properties.rpmsave"
perfcharts_config_file_new_path = "/var/lib/vmware-perfcharts/config/log4j.properties"


def doPatching(ctx):
    logger.info("Patching Performance Charts Service")

    if Path(perfcharts_config_file_path).is_file():
        shutil.copy(perfcharts_config_file_path, perfcharts_config_file_new_path)
    elif Path(perfcharts_config_file_path_suffix).is_file():
        shutil.copy(perfcharts_config_file_path_suffix, perfcharts_config_file_new_path)

    os.chown(utils.perfcharts_props_file, 1011, 0)
    perfchartsSpec = os.path.join(utils.get_config_dir(),
                              'perfchartsspec.properties')
    os.chown(perfchartsSpec, 1011, 0)
    catalinaProp = os.path.join(utils.get_tc_instance_dir(), 'conf',
                                'catalina.properties')
    os.chown(catalinaProp, 1011, 0)
    wrapper = os.path.join(get_component_home_dir(COMPONENT), 'wrapper',
                           'conf', 'wrapper.conf')
    os.chown(wrapper, 1011, 0)
    heapsizeWrapper = os.path.join(get_component_home_dir(COMPONENT), 'wrapper',
                           'bin', 'heapsize_wrapper.sh')
    os.chown(heapsizeWrapper, 1011, 0)

    logger.info("Completed patching Performance Chart Service")


def is_patch_needed(prop_file):
    return utils.is_patch_needed(int(PATCH_VERSION), prop_file)


def doExpand(ctx):
    logger.info("No expand for version 4 on perfCharts service")


def doContract(ctx):
    logger.info("No contract for version 4 on perfCharts service")
