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

import os
import sys
import logging
from l10n import msgMetadata as _T, localizedString as _

VPXD_SVCS_PATCHES_DIR = os.path.dirname(os.path.dirname(__file__))
sys.path.append(VPXD_SVCS_PATCHES_DIR)
sys.path.append(os.environ['VMWARE_PYTHON_PATH'])
sys.path.append(os.path.dirname("/usr/lib/vmware-cm/bin/"))
from cis.utils import FileBuffer, readprop, replace_properties_in_file
from cis.vecs import vmafd_machine_id
from cloudvmcisreg import (cloudvm_sso_cm_register, VecsKeyStore,
                           read_service_id, write_service_id)
from constants import DATASERVICES_PROP, CPSPEC_PROP, CPSPEC_PROP_NEW, VERSION
from patch_errors import InternalError
from utils import is_vmc_gateway

logger = logging.getLogger(__name__)
soluser = "vpxd-extension"
sol_id = "{}-{}".format(soluser, vmafd_machine_id())


def getChanges():
    return _(_T("vpxd-svcs.patch.summary",
                "Reregisters Compute Policy with http URL for metadata on "
                "Lookup Service and updates rhttpproxy configuration."))


def update_registration():
    """Reregisters Compute Policy with http URL for meatadata."""
    try:
        keystore = VecsKeyStore(soluser)
        port = readprop(DATASERVICES_PROP, "dataservice.http.port")
        dyn_vars = {'vpxd-svcs.int.endpoint-http': port,
                    'solution-user.name': sol_id}
        cp_spec_buf = FileBuffer()
        cp_spec_buf.readFile(CPSPEC_PROP)
        service_id, unused = read_service_id(cp_spec_buf, None)
        write_service_id(CPSPEC_PROP_NEW, service_id)
        logger.info("Compute-policy service id: {}".format(service_id))
        cloudvm_sso_cm_register(keystore, CPSPEC_PROP_NEW,
                                soluser, dynVars=dyn_vars, regOp='tryupgrade',
                                isPatch=True)
        os.rename(CPSPEC_PROP_NEW, CPSPEC_PROP)
        logger.info("Compute Policy reregistered with http URL for metadata on "
                    "Lookup Service")
    except Exception as e:
        logger.error(e)
        logger.error("Compute Policy reregistration with http URL for metadata"
                     " on Lookup Service failed")
        raise InternalError("VMware vCenter-Services patch failed")


def doPatching(ctx):
    if is_vmc_gateway():
       return
    logger.info("vpxd-svcs.patch: being executed %s", ctx)
    """
    This patch
    needs to update the LS registration with the http configuration
    for compute policy metadata.
    """
    update_registration()
    replace_properties_in_file(DATASERVICES_PROP, {VERSION: 8})
