#!/usr/bin/env python
#
# Copyright 2017 VMware, Inc.  All rights reserved. -- VMware Confidential
#
"""
This module contains helper functions for get/set the vSphere Client version.
"""

import logging
import os
from distutils.version import LooseVersion

logger = logging.getLogger(__name__)


CONFIG_DIR = '/etc/vmware'
BUILD_INFO_FILE = os.path.join(CONFIG_DIR, '.buildInfo')
H5C_CONFIG_DIR = os.path.join(CONFIG_DIR, 'vsphere-ui')
H5C_VERSION_FILE = os.path.join(H5C_CONFIG_DIR, 'version.txt')


def get_client_version():
    """
    Try to get the version from {H5C_VERSION_FILE} or from {BUILD_INFO_FILE} as fallback.

    :return: Current version of the vSphere Client.
    :rtype: LooseVersion
    """

    version_str = None
    if os.path.exists(H5C_VERSION_FILE) and os.path.isfile(H5C_VERSION_FILE):
        logger.info('Reading version from file: %s' % H5C_VERSION_FILE)
        with open(H5C_VERSION_FILE, 'r') as file_in:
            version_str = file_in.readline()
            version_str = version_str.strip()

    else:
        logger.warn('File does not exist: %s' % H5C_VERSION_FILE)

    if not version_str:
        # Get the version from the /etc/vmware/.buildInfo file
        version_str = _get_client_version_from_build_info_file()

    # If version_str is None, the Version object will be equal to 0.0.0.0
    result = LooseVersion(version_str)
    logger.info('vSphere Client version: %s' % result)
    return result


def save_client_version(version):
    """
    Save the specified version string in {H5C_VERSION_FILE}.

    :param version: Version string to persist
    :type version: str
    """

    if not os.path.exists(H5C_CONFIG_DIR):
        logger.info('Creating folder %s' % H5C_CONFIG_DIR)
        os.makedirs(H5C_CONFIG_DIR)

    logger.info('Saving vSphere Client version to %s' % H5C_VERSION_FILE)
    with open(H5C_VERSION_FILE, 'w') as file_out:
        file_out.write(str(version))
    logger.info('Done')


def _get_client_version_from_build_info_file():
    """
    Parse {BUILD_INFO_FILE} and read the vSphere Client rpm version.

    :return: Version of the vSphere Client rpm file
    :rtype: str
    """

    if os.path.isfile(BUILD_INFO_FILE):
        logger.info('Reading version from file: %s' % BUILD_INFO_FILE)
        with open(BUILD_INFO_FILE, 'r') as file_in:
            for line in file_in:
                if line.startswith('vsphere_h5client:vsphere-ui-'):
                    # Line looks like this:
                    # vsphere_h5client:vsphere-ui-6.5.0.0-9557036.noarch.rpm
                    version_str = line.replace('vsphere_h5client:vsphere-ui-', '')
                    version_str = version_str.replace('.noarch.rpm', '')
                    version_str = version_str.replace('-', '.')
                    version_str = version_str.strip()
                    return version_str
    else:
        logger.warn('File %s does not exist' % BUILD_INFO_FILE)

    return None
