#!/usr/bin/env python3
# Copyright 2018 VMware, Inc.  All rights reserved. -- VMware Confidential

import os
import sys
import logging

SITE_PACKAGES = os.path.join(os.sep, 'usr', 'lib', 'vmware', 'site-packages')
HOME_DIR = os.path.join(os.sep, 'usr', 'lib', 'vmware-updatemgr')

sys.path.append(SITE_PACKAGES)

from cis.defaults import get_cis_install_dir, get_component_home_dir

CMBin = os.path.join(get_cis_install_dir(),
                     get_component_home_dir("cm"),
                     "bin")
sys.path.append(CMBin)
from cloudvmcisreg import cloudvm_sso_cm_register, VecsKeyStore
from cis.vecs import vmafd_machine_id

logger = logging.getLogger(__name__)

SOLUSER_NAME = 'vpxd-extension'
SOLUSER_ID = "%s-%s" % (SOLUSER_NAME, vmafd_machine_id())
H5_UPDATEMGR_PROPERTIES_FILE = os.path.join(HOME_DIR, 'firstboot',
                                            'updatemgr-h5.properties')

def doPatching(ctx):
    """The function performs following tasks related to patch2_0 of
    VMware-UpdateManager:
    1) Register H5 UI client information.
    """
    logger.info("Patch2_0: being executed %s", ctx)
    registerWithCM(H5_UPDATEMGR_PROPERTIES_FILE)


def registerWithCM(property_file):
    """The function will perform VUM client's registration during b2b update.

    @param property_file: The template property file  of the client

    @raise InternalError: If the property file is missing or failed to
    register the client information.
    """
    logger.info("Enter registerWithCM.")
    # Check for file existence.
    if not os.path.exists(property_file):
        logger.error("%s does not exist. Skipping client registration.",
                     str(property_file))
        raise InternalError("VMware-UpdateManager patch failed.")

    # In case of VUM, during firstboot the keystore
    # is initialize using "vpxd-extension" soluser_name.
    logger.info("soluser_name: %s, soluser_id: %s" % (SOLUSER_NAME, SOLUSER_ID))
    keystore = VecsKeyStore(SOLUSER_NAME);
    controlScript = 'service-control-default-vmon'
    specProps = {
                  'solution-user.name' : SOLUSER_ID,
                  'unsupported.action' : 'SET_STARTUPTYPE_DISABLED',
                  'control.script': controlScript
                }
    try:
        logging.info("Register service with CM...")
        svcInfo = cloudvm_sso_cm_register(keystore, property_file,
                                          SOLUSER_NAME, specProps)
        if not svcInfo:
            logging.error("Service registration with CM returned empty service information.")
            raise InternalError("VMware-UpdateManager patch failed.")

        logging.info("Service Registration completed successfully. ServiceId: %s,"
                     " ownerId: %s" %(svcInfo['serviceId'], svcInfo['ownerId']))
    except Exception as err:
        logging.error("Failed to register service with CM. Property File: " +
                      str(property_file) + ", Reason: " + str(err))
        raise InternalError("VMware-UpdateManager patch failed.")
