#!/usr/bin/env python

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

sys.path.append(os.environ['VMWARE_PYTHON_PATH'])
sys.path.append(os.path.dirname("/usr/lib/vmware-cm/bin/"))
from shutil import copyfile
from cis.defaults import *
from cis.utils import *
from cis.tools import *
from cis.exceptions import *
from cis.firstboot import *
from cis.security import *
from cloudvmcisreg import *
from extensions import extend, Hook
import utils

logger = logging.getLogger(__name__)

PERFCHARTS_COMPONENT = 'perfcharts'
SOLUTION_USER_NAME = "vsphere-webclient"
PATCH_VERSION='1'

# refer: http://support.microsoft.com/kb/243330/
WINDOWS_ADMINISTRATORS_SID = "S-1-5-32-544"

CIS_HOME = os.environ.get('VMWARE_CIS_HOME', '')

def doPatching(ctx):
    logger.info("Patching Performance Charts Service")
    logger.info("Registering with lookup service")

    keystore = VecsKeyStore(SOLUTION_USER_NAME)
    control_script = 'vmware-perfcharts' + def_by_os('.sh', '.bat')
    logger.info("control_script = "+control_script)

    logger.info("Replacing the variables in new configuration files")
    lookupsvc_spec_new = os.path.join(utils.get_config_dir(), "perfchartsspec.properties.rpmnew")
    perfcharts_prop_file_new = os.path.join(utils.get_config_dir(), 'perfcharts.properties.rpmnew')
    # Replace the variables in the properties file
    vcdb_conf_path = def_by_os(os.path.join('%s-%s' % (get_cis_config_dir(),'vpx'),'vcdb.properties'),
                                       os.path.join(get_cis_config_dir(),'vmware-vpx','vcdb.properties'))
    db_type = readprop(vcdb_conf_path, 'dbtype')
    sca_url = "http://localhost:{0}/sca/sdk".format(get_install_parameter('sca.int.scahttp'))
    logger.info(sca_url)
    try:
         hostid = wait_for_install_parameter('sca.hostid')
    except InstallParameterException as e:
         log_error(e)
         raise createBaseInstallException(
            _T('install.perfcharts.error.install_parameter.sca.hostid',
               'Error getting install-parameter "sca.hostid".'),
            problemId = 'install.perfcharts.error.install_parameter.sca.hostid')

    if os.path.isfile(perfcharts_prop_file_new):
       f = FileBuffer()
       f.readFile(perfcharts_prop_file_new)
       f.findAndReplace('##{SCA_URL}##', sca_url)
       f.findAndReplace('##{PERFCHARTS_HOST_ID}##', hostid)
       f.findAndReplace('##{PERFCHARTS_KEYSTORE_NAME}##', SOLUTION_USER_NAME)
       f.findAndReplace('##{PERFCHARTS_CERT_ALIAS}##', SOLUTION_USER_NAME)
       f.findAndReplace('##{PERFCHARTS_KEY_ALIAS}##', SOLUTION_USER_NAME)
       f.findAndReplace('##{PERFCHARTS_VDB_CONFIG_PATH}##', to_unix_path(vcdb_conf_path))
       f.findAndReplace('##{PERFCHARTS_LOG_PATH}##', to_unix_path(utils.get_log_dir()))
       f.writeFile(perfcharts_prop_file_new)
       f.clearBuffer()

    cisregSpec = os.path.join(utils.get_config_dir(), "perfchartsspec.properties")
    perfcharts_prop_file = os.path.join(utils.get_config_dir(), 'perfcharts.properties')
    perfcharts_tcinstance_dir = utils.get_tc_instance_dir()
    if os.path.isfile(perfcharts_prop_file_new):
       os.rename(perfcharts_prop_file_new,perfcharts_prop_file)

    if os.path.isfile(lookupsvc_spec_new):
       os.rename(lookupsvc_spec_new,cisregSpec)
    logger.info("Property File update is complete")

    logger.info("Loading Properties File")
    perfcharts_properties = {}
    perfcharts_properties = read_properties(perfcharts_prop_file,
                                             ["perfcharts.path",
                                              "perfcharts.healthstatus.path",
                                              "perfcharts.resourcebundle.basename",
                                              "perfcharts.entry.path"
                                             ])

    dynVars = {'perfcharts.healthstatus.path' : perfcharts_properties['perfcharts.healthstatus.path'],
               'perfcharts.resourcebundle.path' : perfcharts_properties['perfcharts.path'] + '/resourcebundle',
               'perfcharts.path' : perfcharts_properties['perfcharts.path'],
               'perfcharts.entry.path' : perfcharts_properties['perfcharts.entry.path'],
               'perfcharts.resourcebundle.basename' : perfcharts_properties['perfcharts.resourcebundle.basename'],
               'controlscript.path' : control_script,
               'solution-user.name' : SOLUTION_USER_NAME}

    statsreport_dir = os.path.join(perfcharts_tcinstance_dir, 'webapps', 'statsreport')
    web_inf = os.path.join(statsreport_dir, 'WEB-INF')
    metadataDir = os.path.join(web_inf, 'classes', 'metadata')
    logger.info("Metadata Directory %s",metadataDir)
    file_buff = FileBuffer()
    if os.path.isfile(cisregSpec):
       file_buff.readFile(cisregSpec)
       file_buff.findAndReplace('##{VAPI_METADATA_PATH}##', metadataDir)
       file_buff.findAndReplace('#endpoint1','endpoint1')
       file_buff.writeFile(cisregSpec)
       file_buff.clearBuffer()
    try:
       cloudvm_sso_cm_register(keystore,
                               cisregSpec,
                               SOLUTION_USER_NAME,
                               dynVars,
                               regOp='tryupgrade')
    except BaseException as e:
       log_error(e)
       raise createBaseInstallException(
          _T('install.perfcharts.error.sso_cm_register',
             'Failed to register VMware Performance Charts Service'
             ' with Single Sign On/Component Manager associated with'
             ' file : %(0)s'),
          detail_args=[cisregSpec],
          problemId = 'install.perfcharts.error.sso_cm_register')
    logger.info('Successfully registered TOPN Service Service with the '
         'Component Manager.')
    logger.info('Successfully updated the patch version')

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 1 on perfCharts service")

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