#!/usr/bin/env python

#
# Copyright 2018-2021 VMware, Inc.  All rights reserved. -- VMware Confidential
#
'''
Utilities module
'''
import logging
import os
import sys
import platform
import shutil

sys.path.append(os.environ['VMWARE_PYTHON_PATH'])
from cis.utils import readprop, replace_properties_in_file, write_props_to_file
from cis.defaults import *

COMPONENT_NAME = 'perfcharts'
PERFCHARTS_PATCH_KEY = 'perfcharts.patch.version'
logger = logging.getLogger(__name__)

def get_config_dir():
   if platform.system().lower() == "windows":
      return get_cis_config_dir()
   else:
      return '/etc/vmware-%s/' % COMPONENT_NAME

__VERSION_FILE_NAME__ = 'perfcharts.properties'
__VERSION_FILE__ = '%s/perfcharts.properties' % get_config_dir()
perfcharts_props_file = '%s/perfcharts.properties' % get_config_dir()


def get_log_dir():
    return os.path.join(get_cis_log_dir(), COMPONENT_NAME)

def getSourceVersion(parentDir, fileName=__VERSION_FILE_NAME__):
    ''' Loads current component version from file located at @parentDir
    and named @fileName
    '''
    filePath = os.path.join(parentDir, fileName)
    if os.path.exists(filePath):
            version = readprop(filePath, PERFCHARTS_PATCH_KEY)
    else:
        version = None
    return version

def preserveVersionFile(stageDir, filePath=__VERSION_FILE__):
    """ Persists the version file in the stage directory

    @param stageDir: Directory to preserve the version file in.
    """
    if os.path.exists(filePath):
        shutil.copy(filePath, stageDir)
    else:
        logger.info("Version file doesn't exist!! This may be a fresh install of vstats")

# This method is used to determine if a patch is needed based on the patch
# version in the  file.
def is_patch_needed(version, prop_file):
    perfcharts_patch_props_before = readprop(prop_file, PERFCHARTS_PATCH_KEY)
    logger.info("Version found: (before, %s)" % perfcharts_patch_props_before)
    if perfcharts_patch_props_before is None or (int(perfcharts_patch_props_before) < version):
        logger.info("Either patch version isn't in perfcharts.properties or current "
                    "version is less than %d, there is a patch to apply"
                    % (version))
        return True
    logger.info("There is no patch to apply based on patch version")
    return False

# This method updates the patch version inside perfcharts.properties after a patch
# has been applied
def update_patch_version(version, prop_file):
    perfcharts_props_version = readprop(prop_file, PERFCHARTS_PATCH_KEY)
    prop = {PERFCHARTS_PATCH_KEY: version}
    logger.info("Propertise to update = %s", prop)
    if perfcharts_props_version is None:
        with open(prop_file, "a") as myFile:
           myFile.write(PERFCHARTS_PATCH_KEY + '=' + version)
           myFile.close()
        logger.info("Successfully written the new patch version")
    else:
        replace_properties_in_file(prop_file, prop)
        logger.info("Successfully replaced the new patch version")


# This method will get the perfcharts config directory based on the os.
def get_tc_instance_dir():
    return os.path.join(get_component_home_dir(COMPONENT_NAME), 'tc-instance')

