#!/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, arch_matches


def add_arch(toarch, inSources, outSources, verbose=False):
    nr_modified = 0
    nr_all = 0
    for pkg in inSources:
        nr_all += 1
        arch = pkg['Architecture']
        if not any([arch_matches(toarch, a) for a in arch.split()]):
            pkg['Architecture'] = arch + " " + toarch
            nr_modified += 1

    with outSources as outfile:
        for pkg in inSources:
            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=("Add architecture toarch to all source packages in" +
                     " inSources which do not match toarch yet."))
    parser.add_argument('toarch', help='architecture to add')
    parser.add_argument(
        'inSources', type=read_tag_file, help='input Sources file')
    parser.add_argument(
        'outSources', type=get_fh_out, help='output Sources file')
    parser.add_argument(
        '-v', '--verbose', action='store_true', help='be verbose')
    args = parser.parse_args()
    ret = add_arch(args.toarch, args.inSources, args.outSources, args.verbose)
    exit(not ret)
