# Copyright (c) 2015 VMware, Inc.  All rights reserved.
# -- VMware Confidential

import os
import shutil

__VERSION_FILE_NAME__ = "version.txt"
__VERSION_FILE__ = "/etc/vmware-rhttpproxy/{0}".format(__VERSION_FILE_NAME__)


def getSourceVersion(stageDir):
    """ Loads current component version from stageDir.

    The version file gets preserved into the patch stage dir before the RPM
    installation replaces that file.

    @param stageDir: Path to the directory of the source version file.
    """

    filePath = os.path.join(stageDir, __VERSION_FILE_NAME__)

    if os.path.exists(filePath):
        with open(filePath) as fp:
            version = fp.read().strip()
    else:
        version = None
    return version


def setSourceVersion(version, filePath=__VERSION_FILE__):
    """ Persists the latest applied patch version.

    The assumed source of truth is the $filePath.new file.

    If $filePath.new doesn't exist then the RPM already installed $filePath.

    If for some reason $filePath.new can't replace $filePath then the filePath
    is manually filled with the latest version.

    @param version: The latest patch version.
    @param filePath: Path to the component version file.
    """

    newFilePath = "{0}.new".format(filePath)

    if os.path.exists(newFilePath):
        try:
            shutil.move(newFilePath, filePath)
        except:
            with open(filePath, "w") as fp:
                fp.write(version)


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

    @param stageDir: Directory to preserve the version file in.
    """

    if os.path.exists(filePath):
        shutil.copy(filePath, stageDir)
