#!/usr/bin/env python3

from __future__ import print_function
import sys

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


def convert_arch(fromarch, toarch, inPackages, outPackages, verbose=False):
    nr_modified = 0
    nr_all = 0
    for pkg in inPackages:
        nr_all += 1
        arch = pkg["Architecture"]
        if arch == fromarch:
            pkg["Architecture"] = toarch
            nr_modified += 1

    with outPackages as outfile:
        for pkg in inPackages:
            pkg.dump(outfile)
            outfile.write(b"\n")

    if verbose:
        print("modified %d out of %d packages" % (nr_modified, nr_all), file=sys.stderr)

    return True


if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser(
        description=(
            "convert architecture of a Packages file from fromarch " + "to toarch"
        )
    )
    parser.add_argument("fromarch", help="architecture to convert from")
    parser.add_argument("toarch", help="architecture to convert to")
    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("-v", "--verbose", action="store_true", help="be verbose")
    args = parser.parse_args()
    ret = convert_arch(
        args.fromarch, args.toarch, args.inPackages, args.outPackages, args.verbose
    )
    exit(not ret)
