#!/usr/bin/env python

#
# Copyright 2020 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

_RPMNEW_EXT = '.rpmnew'
LS_SPEC_FILE_PATH = '/usr/lib/vmware-infraprofile/config/infraprofile-ls-spec.properties'
_LS_SPEC_FILE_PATH_NEW = LS_SPEC_FILE_PATH + _RPMNEW_EXT

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

from cis.tools import run_command

logger = logging.getLogger(__name__)

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

    # Check if there is a new lookup service spec.
    if not os.path.isfile(_LS_SPEC_FILE_PATH_NEW):
        return

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

    logDir = settings.loggingData.directory
    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")
