#!/usr/bin/env python
# Copyright 2016-2020 VMware, Inc.
# All rights reserved. -- VMware Confidential

import os
import subprocess
import sys
import tempfile

sys.path.append(os.getenv('VMWARE_PYTHON_PATH'))

from cis.firstboot import FirstBoot
from cis.defaults import get_component_home_dir

sys.path.append(os.path.join(get_component_home_dir('cm'), 'bin'))

from cloudvmcisreg import cloudvm_sso_cm_register, VecsKeyStore

class MbcsFirstBoot(FirstBoot):
    def __init__(self, comp_name, soluser_name):
        super(MbcsFirstBoot, self).__init__(comp_name, soluser_name)

    def unregister(self, specFile):
        keystore = VecsKeyStore(self.get_soluser_name())
        dynVars = {
            'solution-user.ownerId' : self.get_soluser_ownerId(),
            'solution-user.name' : self.get_soluser_id(),
            'svcaccountmgmt.metadata-path' : '/usr/lib/vmidentity/install/svcaccountmgmt',
        }
        cloudvm_sso_cm_register(keystore, specFile, self.get_soluser_name(),
            regOp='unregister', local=True, dynVars=dynVars)

def main():
    process = subprocess.run(["/usr/lib/vmware-lookupsvc/tools/lstool.py", "list",
        "--no-check-cert", "--url", "https://localhost/lookupservice/sdk",
        "--type", "messagebus.config", "--as-spec"],
        stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
    serviceId = None
    for line in process.stdout.decode("utf-8").splitlines():
        if line.startswith("serviceId="):
            serviceId = "cmreg.serviceid=" + line[10:] + "\n"
            break

    if serviceId == None:
        print("MBCS Service not found.")
    else:
        with tempfile.NamedTemporaryFile() as temp:
            temp.write(serviceId.encode("utf-8"))
            temp.write(process.stdout)

            firstBoot = MbcsFirstBoot("mbcs", "vpxd-extension")
            firstBoot.unregister(temp.name)

if __name__ == '__main__':
    main()
