#!/usr/bin/env python

#
# Copyright 2020 VMware, Inc.  All rights reserved. -- VMware Confidential
#
"""
Utilities module
"""
import logging
import os
import sys
import shutil
import json
from collections import OrderedDict

sys.path.append(os.environ['VMWARE_PYTHON_PATH'])

COMPONENT_NAME = 'infraprofile'
IPM_PATCH_KEY = 'infraprofile.patch.version'

logger = logging.getLogger(__name__)

def get_config_dir():
    return '/usr/lib/vmware-%s/config' % COMPONENT_NAME

__PROP_FILE_NAME__ = "infraprofile.properties"
__PROP_FILE__ = "{0}/{1}".format(get_config_dir(),__PROP_FILE_NAME__)

def getCurrentVersion(stageDir):
    """ Loads current component version from stageDir.

    The version file gets preserved into the patch stage dir before the RPM
    installation replaces that file.

    @param stageDir: Path to the directory of the source version file.
    """

    from cis.utils import readprop

    filePath = os.path.join(stageDir, __PROP_FILE_NAME__)

    if os.path.exists(filePath):
        version = readprop(filePath, IPM_PATCH_KEY)
    else:
        version = None
    return version

# This method is used to determine if a patch is needed based on the patch
# version in the infraprofile.properties file.
def is_patch_needed(stageDir, version):
    from cis.utils import readprop

    current_ver = getCurrentVersion(stageDir)

    logger.info("Version found: (before, %s)" % current_ver)

    if current_ver is None or (float(current_ver) < float(version)):
        logger.info("Either patch version isn't in infraprofile.properties or current "
                    "version is less than %f, there is a patch to apply"
                    % float(version))
        return True

    logger.info("There is no patch to apply based on patch version")
    return False

# This method updates the patch version inside infraprofile.properties after a patch
# has been applied
def update_patch_version(version):
    from cis.utils import readprop, replace_properties_in_file, write_props_to_file

    ipm_patch_prop_version = readprop(__PROP_FILE__, IPM_PATCH_KEY)

    prop = {IPM_PATCH_KEY: version}

    if ipm_patch_prop_version is None:
        write_props_to_file(__PROP_FILE__, prop)
    else:
        replace_properties_in_file(__PROP_FILE__, prop)

# The file will be installed as part of the rpm. During b2b upgrade, we need
# to backup its original content before the rpm overwrites the original file
# (@Prepatch hook)
def preserve_prop_file(stageDir, filePath=__PROP_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 Infra Profile Service")
