#!/usr/bin/env python
#
# Copyright 2016-2017 VMware, Inc.  All rights reserved. -- VMware Confidential
#
"""
This module contains helper functions for reading/writing
the version of vAPI Endpoint.
Copied from NGC with slight modifications:
//depot/vsphere-client-modules/
   vmkernel-main/assembler/patch/vsphere_client/version_util.py
"""

import logging
import os
from distutils.version import LooseVersion

logger = logging.getLogger(__name__)

CONFIG_DIR = os.path.join(os.path.abspath(os.sep), 'etc', 'vmware-vapi')
VERSION_FILE = os.path.join(CONFIG_DIR, 'b2b_version.txt')
TEMP_VERSION_FILE = os.path.join(CONFIG_DIR, 'b2b_temp_version.txt')


def initialize():
   """
   Copies the version from b2b_version.txt to b2b_temp_version.txt so that it
   can be read after the rpm overrides b2b_version.txt.
   Removes b2b_temp_version.txt first if present.
   """
   remove_temp_version()
   version_str = _read_version_from_file(VERSION_FILE)
   if version_str is not None:
      logger.info('Creating temporary version file: %s' % TEMP_VERSION_FILE)
      with open(TEMP_VERSION_FILE, 'w') as f:
         f.write(version_str)


def get_version():
   """
   Retrieves the version from {TEMP_VERSION_FILE}. Returns 1.0.0.0 if the file
   does not exist.

   :return: Current version of the component if it exists; otherwise, 1.0.0.0
   :rtype: LooseVersion
   """

   version_str = _read_version_from_file(TEMP_VERSION_FILE)
   if version_str is None:
      # This can happen when upgrading from vSphere 6.5, 6.5ep1 or 6.5p01 as
      # b2b_version.txt is not present there so b2b_temp_version.txt won't be
      # available too.
      version_str = '1.0.0.0'
      logger.info('No temporary version file: %s' % TEMP_VERSION_FILE)

   result = LooseVersion(version_str)
   logger.info('vAPI Endpoint version: %s' % result)
   return result

def _read_version_from_file(file_path):
   """
   Returns the first line of the specified file.

   :param file_path: The path to the version file
   :return: The  version if the file exists; otherwise None
   """

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

   return None

def remove_temp_version():
   """
    Deletes the {TEMP_VERSION_FILE} if present.
   """

   if os.path.isfile(TEMP_VERSION_FILE):
      logger.info('Deleting temporary version file: %s' % TEMP_VERSION_FILE)
      os.remove(TEMP_VERSION_FILE)

