#!/usr/bin/env python

#
# Copyright 2017 VMware, Inc.  All rights reserved. -- VMware Confidential
#
"""
Patch script that does the following:
1) updates the domain id in LDAP
2) renames the link properties file with the corrected
   domain id.
"""
import codecs
import logging
import os
import os.path
import re
import sys
import warnings
from cis.utils import readprop

import os_utils
from os_utils import executeCommand
import utils

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

PATCH_VERSION = '2'
COMPONENT_NAME = 'hvc'
LOG4J_PROP_PATH = os.path.join('/usr/lib/vmware-hvc/config/', 'log4j.properties')
VMWARE_JAVA_SEC_PROP_PATH = os.path.normpath(os.path.join(os.environ['VMWARE_CFG_DIR'], 'java', 'vmware-override-java.security'))
HVC_LOGDIR = '/var/log/vmware/hvc'

#Common jars dependencies.
VMWARE_COMMON_JARS_DIR = os.environ['VMWARE_COMMON_JARS']
VMWARE_COMMON_JARS = ["jna.jar", "platform.jar", "aopalliance-1.0.jar",
    "commons-pool-1.6.jar", "commons-codec-1.10.jar", "commons-lang3-3.4.jar",
    "commons-lang-2.6.jar", "commons-logging-1.2.jar", "jackson-annotations-2.4.4.jar",
    "jackson-core-2.4.4.jar", "jackson-core-asl-1.9.13.jar",
    "jackson-databind-2.4.4.jar", "jackson-mapper-asl-1.9.13.jar",
    "jamon-2.81.jar", "log4j-1.2.17.jar", "slf4j-api-1.7.12.jar",
    "slf4j-log4j12-1.7.12.jar", "spring-aop-4.2.5.RELEASE.jar",
    "spring-beans-4.2.5.RELEASE.jar", "spring-context-4.2.5.RELEASE.jar",
    "spring-core-4.2.5.RELEASE.jar", "spring-expression-4.2.5.RELEASE.jar",
    "tomcat-embed-core-8.5.15.jar", "woodstox-core-asl-4.4.1.jar",
    "httpcore-4.3.2.jar", "httpclient-4.3.3.jar",
    "stax2-api-3.0.1.jar", "google-collections-1.0.jar"]

# HVC jars
HVC_LIB = '/usr/lib/vmware-hvc/lib/*';

jars = [];
for jar in VMWARE_COMMON_JARS:
    jars.append(os.path.join(VMWARE_COMMON_JARS_DIR, jar))
jars.append(HVC_LIB)
classPath = os.pathsep.join(jars)

logger = logging.getLogger(__name__)

def doPatching(ctx):
    logger.info("hvc patch: being executed %s", ctx)
    javaCommand = os.environ['VMWARE_JAVA_HOME'] + os.sep + "bin" + os.sep + "java"

    # Main patch program
    upgradePatch = "com.vmware.hvc.upgrade.UpgradeDomainId"

    # Run the command
    logger.info("Patch command to be run with classpath : %s",(classPath))
    patchCommand = [javaCommand, '-Xms256m', '-Xmx512m',
                       '-Dlog4j.configuration=file:%s' % LOG4J_PROP_PATH,
                       '-Dvim.logdir=%s' % HVC_LOGDIR,
                       '-Djava.security.properties=%s' % VMWARE_JAVA_SEC_PROP_PATH,
                       '-classpath', classPath, upgradePatch]
    logger.info("Patch command to be executed: %s", (patchCommand))
    stdout, stderr, returnCode,  = executeCommand(patchCommand)
    logger.info("Return code : %s" %(returnCode))
    logger.info("Stdout : %s" %(stdout))
    logger.info("Stderr : %s" %(stderr))
    if (returnCode != 0):
        raise Exception("Upgrade domain id patch failed")
    utils.update_patch_version(PATCH_VERSION)
    logger.info("HVC domain id is successfully patched")

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

def get_link_file_dir():
    return '/etc/vmware-hvc-svc/linkedVcsConfigFiles'

def is_patch_needed():
    # If link file directory does not exist, no need to patch
    link_file_dir_exists = os.path.exists(get_link_file_dir())
    if not link_file_dir_exists:
         return False

    hvc_link_passed = False
    hvc_link_version = None
    for link_file_name in os.listdir(get_link_file_dir()):
       hvc_link_file_path = os.path.join(get_link_file_dir(), link_file_name)
       logger.info("Reading link file %s" %(hvc_link_file_path))
       hvc_link_passed = readprop(hvc_link_file_path, "hvc.link.successful")
       if hvc_link_passed == 'true':
           hvc_link_version = readprop(hvc_link_file_path, "hvc.link.version")
           if (hvc_link_version is None):
               return True
    logger.info("There is no patch to apply.")
    return False
