#!/usr/bin/env python3

import sys
sys.path.append('/usr/share/botch')
from util import read_write_tag_file, parse_dose_yaml, read_yaml_file
from collections import defaultdict


def fix_cross_problems(data, buildpkgs, hostpkgs, verbose=False):
    data = parse_dose_yaml(data)

    if not data.get('bin'):
        return True

    buildpkgdict = defaultdict(list)
    for pkg in buildpkgs:
        buildpkgdict[pkg['Package']].append(pkg)

    hostpkgdict = defaultdict(list)
    for pkg in hostpkgs:
        hostpkgdict[pkg['Package']].append(pkg)

    for pkg, types in list(data['bin'].items()):
        for t in types:
            if t == 'missing':
                # mark binary package m-a:foreign
                if buildpkgdict.get(pkg):
                    newsections = []
                    for section in buildpkgdict[pkg]:
                        section['Multi-Arch'] = 'foreign'
                        newsections.append(section)
                    buildpkgdict[pkg] = newsections
                if hostpkgdict.get(pkg):
                    newsections = []
                    for section in hostpkgdict[pkg]:
                        section['Multi-Arch'] = 'foreign'
                        newsections.append(section)
                    hostpkgdict[pkg] = newsections
            elif t == 'conflict':
                # mark binary package as m-a:same
                if buildpkgdict.get(pkg):
                    newsections = []
                    for section in buildpkgdict[pkg]:
                        section['Multi-Arch'] = 'same'
                        newsections.append(section)
                    buildpkgdict[pkg] = newsections
                if hostpkgdict.get(pkg):
                    newsections = []
                    for section in hostpkgdict[pkg]:
                        section['Multi-Arch'] = 'same'
                        newsections.append(section)
                    hostpkgdict[pkg] = newsections
            else:
                return False

    with buildpkgs as f:
        for k in sorted(list(buildpkgdict.keys())):
            for section in buildpkgdict[k]:
                section.dump(f)
                f.write(b"\n")

    with hostpkgs as f:
        for k in sorted(list(hostpkgdict.keys())):
            for section in buildpkgdict[k]:
                section.dump(f)
                f.write(b"\n")
    return True


if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser(
        description=("fix build and host architecture Packages files " +
                     "according to the result of botch-dose2html"))
    parser.add_argument('data', metavar="dose.yaml", type=read_yaml_file,
                        help="input yaml result as produced by " +
                             "dose-builddebcheck")
    parser.add_argument("buildpackages", type=read_write_tag_file,
                        help="build architecture Packages")
    parser.add_argument("hostpackages", type=read_write_tag_file,
                        help="host architecture Packages")
    parser.add_argument('-v', '--verbose', action='store_true',
                        help="be verbose")
    args = parser.parse_args()
    ret = fix_cross_problems(
        args.data, args.buildpackages, args.hostpackages, args.verbose)
    exit(not ret)
