#!/usr/bin/env python3
"""hos-delta release module: Release related helpers

This module provides handlers for various release related operations.
"""

import os

from hos_delta import utils

def find_baseline_release(image, machine, releases_path, releases_version):
    """Find the baseline release in the provided releases.

    The method goes through the releases, in descending order until it
    finds a baseline. Once identified, the method returns the baseline
    version. Note that the code assumes releases_version is ordered.

    Parameters
    ----------
    image : str
        The image name for which we search the baseline.
    machine : str
        The machine for which we search the baseline.
    releases_path : str
        The path to the directory containing the available releases.
    log : object
        A logging object.

    Returns
    -------
    str
        The baseline version when found, otherwise None.
    """
    for release_version in releases_version[::-1]:
        release_path = os.path.join(releases_path, release_version)
        for _, _, files in os.walk(release_path):
            for _file in files:
                if _file == '%s-%s.baseline' % (image, machine):
                    return release_version
    return None

def find_image_rootfs(release_path, image, machine):
    """Find the root filesystem associated to an image for a specific release.

    Parameters
    ----------
    release_path : str
        Path to the release where the search is carries out.
    image : str
        The image name.
    machine : str
        The machine name.

    Returns
    -------
    str
        The full path of the root filesystem associated to the image and
        machine for the requested release.
    """
    return utils.search_file(release_path, '%s-%s' % (image, machine), ['tar'])

def find_image_fingerprint(release_path, image, machine):
    """Find the root filesystem fingerprint associated to an image for a
    specific release.

    Parameters
    ----------
    release_path : str
        Path to the release where the search is carries out.
    image : str
        The image name.
    machine : str
        The machine name.

    Returns
    -------
    str
        The full path of the root filesystem fingerprint associated to the
        image and machine for the requested release.
    """
    return utils.search_file(release_path, '%s-%s.fingerprint' % (image, machine),
                             ['json', 'json.gz'])
