#!/usr/bin/env python3
#
# merges one or more packages files, taking care that resulting package
# selection is unique in name, arch and version and outputs them in the package
# file given as the last commandline argument
#
# merging just one packages file will remove its duplicates
# output is sorted by name, then by version, then by architecture

import sys
sys.path.append('/usr/share/botch')
from util import get_fh_out, sort_pkgs_key, read_tag_file


def packages_union(inPackages, outPackages, verbose=False):
    result = dict()

    for packages in inPackages:
        for pkg in packages:
            result[(pkg['Package'], pkg['Architecture'], pkg['Version'])] = pkg

    with outPackages as outfile:
        for pkg in sorted(list(result.keys()), key=sort_pkgs_key):
            result[pkg].dump(outfile)
            outfile.write(b"\n")

    return True

if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser(
        description=("merge one or more Packages files"))
    parser.add_argument('inPackages', type=read_tag_file, nargs='+',
                        help="input Packages files")
    parser.add_argument(
        'outPackages', type=get_fh_out, help='output Packages file')
    parser.add_argument('--verbose', action='store_true', help='be verbose')
    args = parser.parse_args()
    ret = packages_union(args.inPackages, args.outPackages, args.verbose)
    exit(not ret)
