#!/usr/bin/env python
#
# Copyright 2019 VMware, Inc.  All rights reserved. -- VMware Confidential
#
"""
Contains a patch script to disable onprem.mode for gateway.

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 logging
import os
import sys
import traceback

if not os.environ['VMWARE_PYTHON_PATH'] in sys.path:
   sys.path.append(os.environ['VMWARE_PYTHON_PATH'])

from cis.utils import FileBuffer
from ..version_util import isVMCGateway

from .base import PatchBase
from l10n import localizedString, msgMetadata as _T
from distutils.version import LooseVersion
from .file_util import add_or_update_property_in_file, get_property_from_file
from .path_constants import H5C_CONFIG_DIR

logger = logging.getLogger(__name__)

class Patch09(PatchBase):
   """
   Patch to enable or disable onprem.mode
   """

   def __init__(self):
      """
      Constructor
      Set the patch version and summary.
      """

      name = "patch_09"
      version = LooseVersion("9.0")
      summary = localizedString(_T(
            "vsphere.ui.patch09.summary",
            "This patch enables onprem.mode flag for onprem and disables for gateway and cloud."))
      PatchBase.__init__(self, name, version, summary)

   def should_patch(self, patch_context):
      """
      :return: Whether the patch should be executed or not
      :rtype: bool
      """
      webclient_properties_file = os.path.join(H5C_CONFIG_DIR, "webclient.properties")
      onprem_mode = get_property_from_file(webclient_properties_file, "onprem.mode")
      if(isVMCGateway() and onprem_mode is None):
         return True
      else:
         return False

   def do_patching(self, patch_context):
      logger.info("Patch09: Disable onprem.mode for gateway")
      webclient_properties_file = os.path.join(H5C_CONFIG_DIR, "webclient.properties")
      try:
         add_or_update_property_in_file(webclient_properties_file, "onprem.mode", "false")
      except:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            errtb = traceback.format_exception(exc_type, exc_value, exc_traceback)
            logger.error("Error updating onprem.mode flag in webclient.properties file:\n " + "".join(errtb))
