#!/usr/bin/env python
# Copyright 2019-2021 VMware, Inc. All rights reserved. -- VMware Confidential
"""
Utilities module
"""

import logging
import os
import sys
COMPONENT_NAME = 'cis-license'
logger = logging.getLogger(__name__)

def run_firstboot(ctx):
   """
   RPM is already run when reached the code here. Hence the imports here are guaranteed
   to be working since they are not referring to modules from the source system anymore.
   """
   logger.info("License patch: being executed %s", ctx)

   logger.info("Running firstboot operations.")

   if not os.environ['VMWARE_PYTHON_PATH'] in sys.path:
      sys.path.append(os.environ['VMWARE_PYTHON_PATH'])

   from cis.defaults import get_cis_install_dir
   from cis.tools import run_command

   COMPONENT_HOME_FOLDER = '%s/vmware-cis-license' % get_cis_install_dir()
   COMPONENT_FIRSTBOOT_PATH = os.path.join(COMPONENT_HOME_FOLDER,
                                           'firstboot',
                                           'license_firstboot.py')

   cmd = [os.environ['VMWARE_PYTHON_BIN'],
          COMPONENT_FIRSTBOOT_PATH,
          '--action',
          'firstboot',
          '--patch']

   rc, stdout, stderr = run_command(cmd)

   if rc != 0:
      logger.info("Firstboot operation execution failed")
      logger.info("\n==========STDOUT============\n")
      logger.info(stdout)
      logger.info("\n=========STDERR=============\n")
      logger.info(stderr)
      logger.info("\n============================\n")
      raise Exception("License Patching failed to execute firstboot operation")

   else:
      logger.info("Successfully ran firstboot operations")


