#!/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 read_diff(filename):
    diff = dict()
    with open(filename) as f:
        for line in f:
            pkg, old, new = line.split()
            pkgname, arch = pkg.split(':')
            diff[(pkgname, arch)] = (old, new)
    return diff


def apply_ma_diff(diff, inPackages, outPackages, verbose=False):
    nr_modified = 0
    nr_all = 0
    for pkg in inPackages:
        nr_all += 1
        if pkg['Architecture'] != 'all':
            arch = 'any'
        else:
            arch = 'all'
        d = diff.get((pkg['Package'], arch))
        if d:
            old, new = d
            if pkg.get('Multi-Arch', 'no') != old \
               and pkg.get('Multi-Arch', 'no') != new:
                print("failed to apply patch because %s is Multi-Arch:%s and"
                      " not Multi-Arch:%s" % (pkg['Package'],
                                              pkg.get('Multi-Arch', 'no'),
                                              old), file=sys.stderr)
                return False
            if pkg.get('Multi-Arch', 'no') == new:
                continue
            pkg['Multi-Arch'] = new
            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=("Apply a multiarch diff as created by botch-ma-diff"))
    parser.add_argument(
        'diff', type=read_diff, help='diff output as created by botch-ma-diff')
    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 = apply_ma_diff(
        args.diff, args.inPackages, args.outPackages, args.verbose)
    exit(not ret)
