#!/usr/bin/env python3

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


def packages_intersection(
        inPackages1, inPackages2, outPackages, verbose=False):
    to_keep = dict()

    for pkg in inPackages2:
        to_keep[(pkg['Package'], pkg['Version'], pkg['Architecture'])] = pkg

    result = dict()

    for pkg in inPackages1:
        name, arch, ver = pkg['Package'], pkg['Version'], pkg['Architecture']
        if to_keep.get((name, arch, ver)):
            result[(name, arch, ver)] = 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=("calculates the intersection of two packages files"))
    parser.add_argument(
        'inPackages1', type=read_tag_file, help='input Packages file #1')
    parser.add_argument(
        'inPackages2', type=read_tag_file, help='input Packages file #2')
    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_intersection(
        args.inPackages1, args.inPackages2, args.outPackages, args.verbose)
    exit(not ret)
