#!/usr/bin/env python

#
# Copyright 2017 VMware, Inc.  All rights reserved. -- VMware Confidential
#
"""
Utilities module
"""
import logging
import os
import sys

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

COMPONENT_NAME = 'hvc'
HVC_PATCH_KEY = 'hvc.patch.version'

logger = logging.getLogger(__name__)


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


# This method is used to determine if a patch is needed based on the patch
# version in the hvc.properties file.
def is_patch_needed(version):
    hvc_props_file_before = '%s/hvc.properties' % get_config_dir()
    hvc_props_before = readprop(hvc_props_file_before, HVC_PATCH_KEY)
    logger.info("Version found: (before, %s)" % hvc_props_before)
    if hvc_props_before is None or (int(hvc_props_before) < version):
        logger.info("Either patch version isn't in hvc.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 hvc.properties after a patch
# has been applied
def update_patch_version(version):
    hvc_props_file = '%s/hvc.properties' % get_config_dir()
    hvc_props_version = readprop(hvc_props_file, HVC_PATCH_KEY)
    prop = {HVC_PATCH_KEY: version}
    if hvc_props_version is None:
        write_props_to_file(hvc_props_file, prop)
    else:
        replace_properties_in_file(hvc_props_file, prop)

