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

import logging
import os
import shutil
import sys

COMPONENT_NAME = 'analytics'

COMPONENT_CFG_FOLDER = '/etc/vmware-%s' % (COMPONENT_NAME)

VERSION_FILE_NAME = 'version.txt'
VERSION_FILE_PATH = os.path.join(COMPONENT_CFG_FOLDER, VERSION_FILE_NAME)

logger = logging.getLogger(__name__)


def preserve_version_file(stage_dir, file_path=VERSION_FILE_PATH):
   """
   Persists the version file in the stage directory
   @param stage_dir: Directory to preserve the version file in.
   @param file_path: Path to version file which to preserve.
   """

   logger.info("Analytics pre-patch. Copying %s to staging", file_path)

   if os.path.exists(file_path):
      shutil.copy(file_path, stage_dir)


def get_current_version(parent_dir, file_name=VERSION_FILE_NAME):
   """
   Loads current component version from file located at @parent_dir
   and named @file_name.
   """

   file_path = os.path.join(parent_dir, file_name)
   logger.info("Analytics patch. Getting current version from %s", file_path)
   if os.path.exists(file_path):
      with open(file_path) as fp:
         version = fp.read()
         logger.info("Analytics patch. Found version %s",
                     version)
   else:
      version = None

   return version


def run_firstboot(ctx):
   """
   RPM is already run when reached the code here. Hence the imports here are guarantee
   to be working since they are not referring to modules from the source system anymore.
   """
   logger.info("Analytics 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-%s' % (get_cis_install_dir(), COMPONENT_NAME)
   COMPONENT_FIRSTBOOT_PATH = os.path.join(COMPONENT_HOME_FOLDER,
                                           'firstboot',
                                           'analytics_firstboot.py')

   cmd = [os.environ['VMWARE_PYTHON_BIN'],
          COMPONENT_FIRSTBOOT_PATH,
          '--action',
          'firstboot',
          '--patch',
          'true']
   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("Analytics Patching failed to execute firstboot operation")
   else:
      logger.info("Successfully ran firstboot operations")


