"""architecture matching

@copyright: 2014, Ansgar Burchardt <ansgar@debian.org>
@copyright: 2014-2017, Johannes Schauer <j.schauer@email.de>
@license: GPL-2+
"""

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

# FIXME: this should be integrated into python-debian
#        see: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=771058

_cached_arch2tuple = None
_cached_tuple2arch = None
_cached_cputable = None


def _load_table(path):
    table = []
    with open(path, "r") as f:
        for line in f:
            if not line or line.startswith("#"):
                continue
            table.append(line.split())
    return table


def _read_cputable():
    global _cached_cputable
    if _cached_cputable is None:
        _cached_cputable = _load_table("/usr/share/dpkg/cputable")
    return _cached_cputable


def _read_tupletable():
    global _cached_arch2tuple, _cached_tuple2arch
    if _cached_arch2tuple is None or _cached_tuple2arch is None:
        table = _load_table("/usr/share/dpkg/tupletable")
        arch2tuple = dict()
        tuple2arch = dict()
        for row in table:
            debtuple = row[0]
            debarch = row[1]
            if "<cpu>" in debtuple:
                for r in _read_cputable():
                    cpu = r[0]
                    dt = debtuple.replace("<cpu>", cpu)
                    da = debarch.replace("<cpu>", cpu)
                    arch2tuple[da] = dt
                    tuple2arch[dt] = da
            else:
                arch2tuple[debarch] = debtuple
                tuple2arch[debtuple] = debarch
        _cached_arch2tuple = arch2tuple
        _cached_tuple2arch = tuple2arch
    return _cached_tuple2arch, _cached_arch2tuple


def debwildcard_to_debtuple(arch):
    arch_tuple = arch.split("-", 3)

    if "any" in arch_tuple:
        if len(arch_tuple) == 4:
            return arch_tuple
        elif len(arch_tuple) == 3:
            return ("any", arch_tuple[0], arch_tuple[1], arch_tuple[2])
        elif len(arch_tuple) == 2:
            return ("any", "any", arch_tuple[0], arch_tuple[1])
        else:
            return ("any", "any", "any", "any")
    else:
        return debarch_to_debtuple(arch)


def debarch_to_debtuple(arch):
    if arch.startswith("linux-"):
        arch = arch[6:]

    tuple = _read_tupletable()[1].get(arch)

    if tuple is None:
        return
    return tuple.split("-", 3)


def match_architecture(real, alias):
    if alias == real or alias == "any":
        return True

    real = debarch_to_debtuple(real)
    alias = debwildcard_to_debtuple(alias)

    if real is None or len(real) != 4 or alias is None or len(alias) != 4:
        return False

    for i in range(0, 4):
        if alias[i] != real[i] and alias[i] != "any":
            return False
    return True
