#!/usr/bin/env python3

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


def filter_src_builds_for(inSources, arch, outSources, verbose=False):
    with outSources as outfile:
        for packages in inSources:
            for pkg in packages:
                if not any([a != "all" and match_architecture(arch, a)
                            for a in pkg['Architecture'].split()]):
                    continue
                pkg.dump(outfile)
                outfile.write(b"\n")
    return True


if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser(
        description=("filter a Sources control file, such that it only "
                     "contains the stanzas for those source packages which "
                     "build binary dependent packages for a certain "
                     "architecture."))
    parser.add_argument('inSources', type=read_tag_file, nargs='+',
                        help="input Sources files")
    parser.add_argument('arch', type=str, help='selected architecture')
    parser.add_argument(
        'outSources', type=get_fh_out, help='output Sources file')
    parser.add_argument('--verbose', action='store_true', help='be verbose')
    args = parser.parse_args()
    ret = filter_src_builds_for(args.inSources, args.arch, args.outSources,
                                args.verbose)
    exit(not ret)
