#!/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'])

COMPONENT_NAME = 'lookupsvc'
LOOKUPSVC_PATCH_KEY = 'lookupsvc.patch.version'

logger = logging.getLogger(__name__)

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

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

    lookupsvc_props_file = '%s/lookupsvc.properties' % get_config_dir()
    lookupsvc_props = readprop(lookupsvc_props_file, LOOKUPSVC_PATCH_KEY)

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

    if lookupsvc_props is None or (int(lookupsvc_props) < int(version)):
        logger.info("Either patch version isn't in lookupsvc.properties or current "
                    "version is less than %d, there is a patch to apply"
                    % int(version))
        return True

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

# This method updates the patch version inside lookupsvc.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

    lookupsvc_props_file = '%s/lookupsvc.properties' % get_config_dir()
    lookupsvc_props_version = readprop(lookupsvc_props_file, LOOKUPSVC_PATCH_KEY)

    prop = {LOOKUPSVC_PATCH_KEY: version}

    if lookupsvc_props_version is None:
        write_props_to_file(lookupsvc_props_file, prop)
    else:
        replace_properties_in_file(lookupsvc_props_file, prop)
