#!/usr/bin/env python

#
# Copyright 2021 VMware, Inc.  All rights reserved. -- VMware Confidential
#
"""
Patch script that does the following:
Update registration to pick new metadata

"""
import logging
import os
import sys

VCLM_DIR = "/usr/lib/vmware-vlcm"
VLCM_PROP = os.path.join(VCLM_DIR, "firstboot", "vlcm_cisreg_spec.properties")

sys.path.append(os.environ['VMWARE_PYTHON_PATH'])
sys.path.append(os.path.dirname("/usr/lib/vmware-cm/bin/"))
sys.path.append(os.path.join(VCLM_DIR, "vlcm"))
from cis.vecs import vmafd_machine_id
from cloudvmcisreg import cloudvm_sso_cm_register, VecsKeyStore
from constants import VLCM_HTTP_PORT, VLCM_STATIC_URL_PORT, VLCM_VERSION, \
     VLCM_SOLUSERNAME

logger = logging.getLogger(__name__)

def doPatching(ctx):
    # Invoke cisreg to re-register vpxd in 'patch' mode
    keystore = VecsKeyStore(VLCM_SOLUSERNAME)
    sol_id = "{}-{}".format(VLCM_SOLUSERNAME, vmafd_machine_id())
    dynVars = {
        'vlcm.solution.user': sol_id,
        'vlcm.int.http': str(VLCM_HTTP_PORT),
        'vlcm.int.http-static': str(VLCM_STATIC_URL_PORT),
        'vlcm.version': str(VLCM_VERSION)
    }
    regOp = 'tryupgrade'
    try:
        logging.info("Invoking Component Manager registration")
        cloudvm_sso_cm_register(keystore, VLCM_PROP, VLCM_SOLUSERNAME,
                                dynVars=dynVars, regOp=regOp,
                                isPatch=True)
        logging.info("Component Manager registration successful")
    except Exception as e:
        errorStr = "Failed to re-registration with Lookup Service. "\
                   "Exception: \n%s" % e
        logging.error(errorStr)
        raise InternalError(errorStr)

