#!/usr/bin/env python3
#
# checks for differences in the multiarch status of packages
#
# can be used to compare the multiarch status of two distributions
# only compares packages that exist in both distributions

from __future__ import print_function
import apt_pkg
from collections import defaultdict
from functools import cmp_to_key
import sys
sys.path.append('/usr/share/botch')
from util import read_tag_file


def ma_diff(packages1, packages2, verbose=False):
    multiarch = defaultdict(set)

    for pkg in packages1:
        if pkg['Architecture'] != 'all':
            arch = 'any'
        else:
            arch = 'all'
        multiarch[(pkg['Package'], arch)].add(
            (pkg['Version'], pkg.get('Multi-Arch', 'no')))

    packages = dict()

    apt_pkg.init()

    # get highest version for each package and check for mixed architecture
    for pkg2 in packages2:
        if pkg2['Architecture'] != 'all':
            arch2 = 'any'
        else:
            arch2 = 'all'
        pkg1 = packages.get((pkg2['Package'], arch2))
        if not pkg1 or (apt_pkg.version_compare(pkg2['Version'],
                        pkg1['Version']) > 0):
            packages[(pkg2['Package'], arch2)] = pkg2

    result = list()

    for pkg in list(packages.values()):
        if pkg['Architecture'] != 'all':
            arch = 'any'
        else:
            arch = 'all'
        pkg1 = multiarch.get((pkg['Package'], arch))
        if not pkg1:
            continue
        # get the package with the highest version number
        pkg1 = sorted(pkg1, key=cmp_to_key(
            lambda a, b: apt_pkg.version_compare(a[0], b[0])))
        _, ma1 = pkg1[-1]
        ma2 = pkg.get('Multi-Arch', 'no')
        if ma2 != ma1:
            result.append((pkg['Package'], arch, ma1, ma2))

    return result


if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser(
        description=("Check for differences in multiarch annotations"))
    parser.add_argument(
        'packages1', type=read_tag_file, help='input Packages file #1')
    parser.add_argument(
        'packages2', type=read_tag_file, help='input Packages file #2')
    parser.add_argument('--verbose', action='store_true', help='be verbose')
    args = parser.parse_args()
    ret = ma_diff(args.packages1, args.packages2, args.verbose)
    for n, a, ma1, ma2 in ret:
        print("%s:%s\t%s\t%s" % (n, a, ma1, ma2))
    exit(bool(ret))
