#!/usr/bin/env python
"""get-latest-swu : Scan path for valid .swu files

__copyright__   = "Copyright (C) 2018 MIND Music Labs
"""

import sys
import os
import io
import libconf
import re

DEFAULT_CPIO_TMP_FILEPATH = '/tmp/_cpio_temp_out'

FIND_VERSION = re.compile(r"""(\d+ \. \d+ \. \d+ .*) \.swu""", re.VERBOSE)


def unpack_version_string(version_str):
    """ Exctract a list of 4 numbers [maj, min, ver, rc]
        to be used for comparing versions.

        If a parsing error occurs, returns [-1, -1, -1, -1]
    """
    try:
        rc_split = version_str.split('-rc')
        if (len(rc_split) == 2):
            rc_num = int(rc_split[1])
            base_version_str = rc_split[0]
        else:
            rc_num = -1
            base_version_str = version_str
        version_split = [ int(x) for x in base_version_str.split('.') ]
        return version_split + [rc_num]
    except:
        return [-1]*4

def get_swus_in_path(path):
    """ Return all .swu files in given path.
        glob module is not available on stripped Python used in ELK builds.
    """
    swus = [ os.path.abspath(os.path.join(path, f)) for f in os.listdir(path) if (os.path.splitext(f)[1] == '.swu') ]
    return swus

def get_version_from_swu(swu_filename):
    """ Extract version information from .swu CPIO archive inside swdescription file.
        Returns version string if found or None otherwise.
    """
    cpio_exec_line = "cpio -i --quiet --to-stdout sw-description < %s > %s 2>/dev/null" % (swu_filename, DEFAULT_CPIO_TMP_FILEPATH)
    cpio_ret = os.system(cpio_exec_line)
    if (cpio_ret == 0):
        try:
            with io.open(DEFAULT_CPIO_TMP_FILEPATH) as f:
                config = libconf.load(f)
                version = str(config['software']['version'])
                return version
        except:
            return None
    else:
        return None

def get_version_from_filename(filename):
    """ Extract version from filename. Less reliable than the one embedded inside the .swu,
        but needed to parse older .swu files which all have '1.0' as their internal version.

        Returns version string if regexp match against filename, None otherwise.
    """
    version_match = FIND_VERSION.findall(filename)
    if not version_match:
        return None
    return version_match[0]

def process_directory(path):
    """ Main loop over a given path.
        Returns the absolute path of the .swu with the highest version if found, or empty string otherwise.
    """
    all_swus = get_swus_in_path(path)
    highest_version = [0] * 4
    highest_file = ''

    for s in all_swus:
        swu_version = get_version_from_swu(s)
        if swu_version is None:
            continue
        # 1.0 needs to be handled differently, because up to 0.7.x series all the swdescription files were
        # using that internally, so we need to parse the filename instead
        if (swu_version == '1.0'):
            current_version = unpack_version_string(get_version_from_filename(s))
        else:
            current_version = unpack_version_string(swu_version)
        if (current_version > highest_version):
            highest_version = current_version
            highest_file = s

    return highest_file


if __name__ == "__main__":
    argc = len(sys.argv)
    if (argc < 2):
        print("\nUsage:")
        print("\n    %s path\n" % sys.argv[0])
        sys.exit(-1)

    print(process_directory(sys.argv[1]))
