#!/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 = 'trustmanagement'
TRUST_PATCH_KEY = 'trustmanagement.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 trustmanagement.properties file.
def is_patch_needed(version):
    # import inside functions (Bug 1972704)
    from cis.utils import readprop

    trust_props_file = '%s/trustmanagement.properties' % get_config_dir()
    trust_props = readprop(trust_props_file, TRUST_PATCH_KEY)

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

    if trust_props is None or (int(trust_props) < int(version)):
        logger.info("Either patch version isn't in trustmanagement.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 trustmanagement.properties after a patch
# has been applied
def update_patch_version(version):
    # import inside functions (Bug 1972704)
    from cis.utils import readprop, replace_properties_in_file, write_props_to_file

    trust_props_file = '%s/trustmanagement.properties' % get_config_dir()
    trust_props_version = readprop(trust_props_file, TRUST_PATCH_KEY)

    prop = {TRUST_PATCH_KEY: version}

    if trust_props_version is None:
        write_props_to_file(trust_props_file, prop)
    else:
        replace_properties_in_file(trust_props_file, prop)
