# Copyright (c) 2017 VMware, Inc.  All rights reserved. -- VMware Confidential

import os
import shutil
import logging

import os_utils
import vcsa_utils
from extensions import extend, Hook
from l10n import msgMetadata as _T, localizedString as _

logger = logging.getLogger(__name__)

@extend(Hook.Discovery)
def discover(ctx):
    """DiscoveryResult discover(PatchContext ctx) throw UserError"""
    logger.info("VCDB VMODL Extension Discovery Hook")
    del ctx # Remove unused reference from current function.
    return vcsa_utils.getComponentDiscoveryResult(
        "dbconfig",
        displayName=_(_T("vcdb_vmodl.b2b.patch.name",
                         "VMware vCenter VCDB VMODL")),
        componentId='vcdb_vmodl_patcher',
        patchServices=[])

OLD_VMWARE_PYTHON_PATH= os.path.join(
    os.path.dirname(os.path.realpath(__file__)),
    "oldPyVmomi")

@extend(Hook.Prepatch)
def prePatch(ctx):
    """void prePatch(PatchContext ctx) throw UserError

    We need to preserve the old pyVmomi before the RPM installation.
    """
    logger.info("VCDB VMODL Extension PrePatch Hook")

    if os.path.exists(OLD_VMWARE_PYTHON_PATH):
        logger.info("Removing the already existing '%s'" %
                    OLD_VMWARE_PYTHON_PATH)
        shutil.rmtree(OLD_VMWARE_PYTHON_PATH)

    logger.info("Preserving the old pyVmomi directory '%s' to '%s'." %
                (os.environ["VMWARE_PYTHON_PATH"], OLD_VMWARE_PYTHON_PATH))
    shutil.copytree(os.environ["VMWARE_PYTHON_PATH"], OLD_VMWARE_PYTHON_PATH)

    vsanmgmt = 'vsanmgmtObjects.py' # @see PR 1904479, PR 1790123
    shutil.copyfile('/usr/lib/vmware-vpx/vsan-health/%s' % vsanmgmt,
                    os.path.join(OLD_VMWARE_PYTHON_PATH, 'pyVmomi', vsanmgmt))

@extend(Hook.Patch)
def patch(ctx):
    """void patch(PatchContext ctx) throw UserError

    This function is too long and needs to be broken down.
    However, it is still unclear what the correct behavior is.
    """
    logger.info("VCDB VMODL Extension Patch Hook")

    patcherPath = os.path.join(os.path.dirname(__file__), 'patcher.py')
    command = ['/usr/bin/python3', patcherPath, ctx.stageDirectory]

    stdout, stderr, exitCode  = os_utils.executeCommand(command)
    logger.info('Vmodl script execution %s', stdout)
    if exitCode:
        logger.error('Vmodl script error %s', stderr)
        raise ValueError('Failed during vmodl patching')
