#!/usr/bin/env python

#
# Copyright 2019-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 traceback

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

from extensions import extend, Hook
import utils
from cis.utils import *

logger = logging.getLogger(__name__)

PERFCHARTS_COMPONENT = 'perfcharts'
PATCH_VERSION='2'


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

    perfcharts_tcinstance_dir = utils.get_tc_instance_dir()
    conf_dir = os.path.join(perfcharts_tcinstance_dir, 'conf')
    catalina_prop_file_new = os.path.join(conf_dir,
                                          'catalina.properties.rpmnew')
    catalina_prop_file = os.path.join(conf_dir, 'catalina.properties')

    http_port_prop = "bio.http.port"
    catalina_properties = read_properties(catalina_prop_file, [http_port_prop])
    current_http_port = catalina_properties[http_port_prop]
    logger.info("Current http.port: %s", current_http_port)

    if os.path.isfile(catalina_prop_file_new):
        catalina_properties_new = read_properties(catalina_prop_file_new,
                                                  [http_port_prop])
        http_port = catalina_properties_new[http_port_prop]
        if http_port != current_http_port:
            f = FileBuffer()
            f.readFile(catalina_prop_file_new)
            f.findAndReplace(http_port, current_http_port)
            f.writeFile(catalina_prop_file_new)
            f.clearBuffer()
            logger.info("Replacing http.port in catalina.properties.rpmnew"
                        " from %s to %s", http_port, current_http_port)
        os.rename(catalina_prop_file_new, catalina_prop_file)

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

# is_patch_needed returns true whenever there is a new catalina.properties.rpmnew file is present.
# catalina.properties.rpmnew file is only generated when there is some diff from the existing one.
# Hence whenever a rpmnew file is observed, it needs to be checked & this patch needs to be executed.
# else the http_port changed as part of patch_02 would not be available
# as it would get overriden. This would lead to Tomcat failure.
def is_patch_needed(prop_file):
    perfcharts_tcinstance_dir = utils.get_tc_instance_dir()
    conf_dir = os.path.join(perfcharts_tcinstance_dir, 'conf')
    catalina_prop_file_new = os.path.join(conf_dir,
                                          'catalina.properties.rpmnew')
    if os.path.isfile(catalina_prop_file_new):
        return True
    return False

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

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