# Copyright 2018 VMware, Inc.  All rights reserved. -- VMware Confidential
# coding: utf-8
import os
import shutil


CONFIG_DIR = '/etc/vmware-vlcm'
# The file will be installed as part of the rpm. During upgrade, we need to read
# its original content before the rpm overwrites the original file, e.g. @Prepatch hook
__VERSION_FILE__ = os.path.join(CONFIG_DIR, 'version.txt')
__VERSION_FILE_NAME__ = os.path.basename(__VERSION_FILE__)


def preserveVersionFile(stageDir, filePath=__VERSION_FILE__):
   """ Persists the version file in the stage directory

   :param stageDir: Directory to preserve the version file in.
   :type stageDir: str
   :param filePath: The filepath to the version file to preserve
   :type filePath: str
   """
   if os.path.exists(filePath):
      shutil.copy(filePath, stageDir)


def getSourceVersion(parentDir, fileName=__VERSION_FILE_NAME__):
   """ Loads current component version from file located at :parentDir
   and named :fileName
   """
   filePath = os.path.join(parentDir, fileName)
   if os.path.exists(filePath):
      with open(filePath) as fp:
         version = fp.read()
   else:
      version = None
   return version
