#!/usr/bin/env python
#
# Copyright 2018 VMware, Inc.  All rights reserved. -- VMware Confidential
#
"""
Contains a patch script that is used when upgrading from vSphere releases, where
the DataService vAPI is deployed with the NGC to ones, deploying it with the H5 client.
Patch scripts must be named "patch_XX.py" and must define a unique sub-class of the
PatchBase abstract class. Patches will be sorted by version and will be applied
incrementally.
"""
import sys
import logging
from .base import PatchBase
from l10n import localizedString, msgMetadata as _T
from distutils.version import LooseVersion
logger = logging.getLogger(__name__)

class Patch2(PatchBase):
    """
    DataService move from NGC to H5 client patch
    """
    def __init__(self):
        """
        Constructor
        Set the patch version and summary.
        """
        version = LooseVersion("6.8.1.9999999")
        summary = localizedString(_T(
                "vsphere.ui.patch02.summary",
                "This patch facilitates the move of DS from NGC to the H5 client"))
        PatchBase.__init__(self, version, summary)

    def do_patching(self, patch_context):
        ds_register_with_cm_location = '/var/vmware-vsphere-ui/scripts'
        if ds_register_with_cm_location not in sys.path:
            logger.info("Patch02: Adding vsphere-ui python scripts to PATH")
            sys.path.append(ds_register_with_cm_location)
        import ds_register_with_cm
        install_dir = "/usr/lib/vmware-vsphere-ui"
        http_port = "5090"
        uninstall_dir = "/usr/lib/vmware-vsphere-client"
        uninstall_port = "9090"
        if hasattr(ds_register_with_cm, "reregister_with_cm"):
            logger.info("Patch02: Reregistering the DataService vAPI Endpoint to LS")
            ds_register_with_cm.reregister_with_cm(install_dir, http_port, uninstall_dir, uninstall_port)
        else:

            raise AttributeError("module 'ds_register_with_cm' has no attribute 'reregister_with_cm'. Please make sure that the source vsphere-h5client is not newer than the destination vsphere-h5client.")

