#!/usr/bin/env python3

import apt_pkg
import sys

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


def single_verson(inPackages, outPackages, verbose=False):
    apt_pkg.init()

    packages = dict()
    for pkg2 in inPackages:
        pkg1 = packages.get((pkg2["Package"], pkg2["Architecture"]))
        if not pkg1 or (apt_pkg.version_compare(pkg2["Version"], pkg1["Version"]) > 0):
            packages[(pkg2["Package"], pkg2["Architecture"])] = pkg2

    with outPackages as outfile:
        for pkg in sorted(packages.keys()):
            packages[pkg].dump(outfile)
            outfile.write(b"\n")

    return True


if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser(
        description=(
            "filters a Packages file so that only the newest "
            + "version of each package remains"
        )
    )
    parser.add_argument("inPackages", type=read_tag_file, help="input Packages file")
    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 = single_verson(args.inPackages, args.outPackages, args.verbose)
    exit(not ret)
