#!/usr/bin/env python

#
# Copyright (c) 2022 VMware, Inc.  All rights reserved.
# -- VMware Confidential
#
"""
Patch script that does the following:

"""
import logging
import os
import re
import sys
import warnings
from os_utils import getCommandExitCode
from vmware_b2b.patching.config import settings
from patch_errors import UserError
from shutil import move

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

from cis.tools import run_command, get_install_parameter
from cis.cisreglib import VmafdClient

logger = logging.getLogger(__name__)

def doPatching(ctx):
    logger.info("Infra Profile Patch being executed %s", ctx)

    logger.info("Fetching infraprofile-lookupservice registration details.")

    logDir = settings.loggingData.directory
    outlsregistration = os.path.join(logDir, 'InfraProfileLookupservice.out.log')
    errlsregistration = os.path.join(logDir, 'InfraProfileLookupservice.err.log')

    vmafd_client = VmafdClient()
    vcHostname = vmafd_client.get_pnid()

    vcPort = int(get_install_parameter("rhttpproxy.ext.port2", "443", quiet=True))

    url = 'https://%s:%d/lookupservice/sdk' % (vcHostname, vcPort)

    logger.info("Lookup service url: %s.", url)

    cmd = ['/usr/lib/vmware-lookupsvc/tools/lstool.py', 'list', '--no-check-cert',
           '--url', url, '--type', 'infraprofile']

    exitCode = getCommandExitCode(cmd, localStdoutFile=outlsregistration,
                                  localStderrFile=errlsregistration)

    with open(outlsregistration) as fp:
        out = fp.read()

    with open(errlsregistration) as fp:
        err = fp.read()

    logger.info("LStool results: exit-code=%s, "
                "stdout=%s, stderr=%s", exitCode, out, err)

    if exitCode != 0:
        cause = 'Failed to get infraprofile-lookupservice registration. Error = %s', err
        raise usererror(cause)

    # Check if infraprofile is already registered with lookup service.
    if ("infraprofile" in out):
        logger.info("Infraprofile service is already registered with Lookup service.")
        return

    # Run FB for Infra Profile service
    cmd = [os.environ['VMWARE_PYTHON_BIN'],
           '/usr/lib/vmware-infraprofile/firstboot/infraprofile_firstboot.py',
           '--action',
           'firstboot']

    outFileName = os.path.join(logDir, 'InfraProfileFirstboot.out.log')
    errFileName = os.path.join(logDir, 'InfraProfileFirstboot.err.log')

    logger.info("Running Firsboot for Infra Profile Service. The immediate command stdout "
                "is redirected to file %s and stderr is redirected to file %s",
                outFileName, errFileName)

    exitCode = getCommandExitCode(cmd,
                                  localStdoutFile=outFileName,
                                  localStderrFile=errFileName)
    with open(outFileName) as fp:
        out = fp.read()

    with open(errFileName) as fp:
        err = fp.read()

    logger.info("Infra Profile Firstboot: command=%s, exit-code=%s, "
                "stdout=%s, stderr=%s", cmd, exitCode, out, err)

    if exitCode != 0:
        cause = 'infraprofile.patch.firstboot.fail: %s' % err
        raise usererror(cause)
    else:
        logger.info("Successfully executed infra profile firstboot operations")
