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

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

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 readprop
from cis.vecs import vmafd_machine_id
from cloudvmcisreg import cloudvm_sso_cm_register, VecsKeyStore
from constants import DATASERVICES_PROP, CPSPEC_PROP
from patch_errors import InternalError

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


def getChanges():
    return _(_T("vpxd-svcs.patch.summary",
                "Registers Compute Policy with Lookup Service."))


def register_cp():
    """Registers Compute Policy with Lookup Service."""
    try:
        keystore = VecsKeyStore(soluser)
        port = readprop(DATASERVICES_PROP, "dataservice.http.port")
        dyn_vars = {'vpxd-svcs.int.endpoint-http': port,
                    'solution-user.name': sol_id}
        cloudvm_sso_cm_register(keystore, CPSPEC_PROP,
                                soluser, dynVars=dyn_vars, regOp='register')
        logger.info("Compute Policy registered on Lookup Service")
    except Exception as e:
        logger.error(e)
        logger.error("Compute Policy registration with 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)
    register_cp()
