#!/usr/bin/env python

#
# Copyright 2018 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 = 'topologysvc'
CERT_PATCH_KEY = 'topologysvc.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 topologysvc.properties file.
def is_patch_needed(version):
    # import inside functions (Bug 1972704)
    from cis.utils import readprop

    certificate_props_file = '%s/topologysvc.properties' % get_config_dir()
    certificate_props = readprop(certificate_props_file, CERT_PATCH_KEY)

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

    if certificate_props is None or (int(certificate_props) < int(version)):
        logger.info("Either patch version isn't in topologysvc.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 topologysvc.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

    certificate_props_file = '%s/topologysvc.properties' % get_config_dir()
    certificate_props_version = readprop(certificate_props_file, CERT_PATCH_KEY)

    prop = {CERT_PATCH_KEY: version}

    if certificate_props_version is None:
        write_props_to_file(certificate_props_file, prop)
    else:
        replace_properties_in_file(certificate_props_file, prop)
