#!/usr/bin/env python3
#
# wget http://bootstrap.debian.net/importance_metric_noall.txt
# ssh buildd_arm64@buildd.debian-ports.org  wanna-build -A arm64 \
#        -d unstable -l  build-attempted > build-attempted
# botch-wanna-build-findblockers build-attempted importance_metric_noall.txt

from __future__ import print_function

__copyright__ = """
Copyright (C) 2014, Chen Baozi <baozich@gmail.com>

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
"""


def read_build_attempted(fname):
    candidates = set()
    with open(fname) as items:
        for line in items:
            if line.startswith("Total"):
                continue
            if line.startswith(" "):
                continue
            candidates.add(line.split()[0].split("/")[1].split("_")[0])
    return candidates


def read_importance_metric(fname):
    priorities = list()
    with open(fname) as metrics:
        for line in metrics:
            priorities.append(line.split())
    return priorities


def main(candidates, priorities, order, vols):
    priorities.sort()
    priorities.sort(key=lambda x: int(x[vols]), reverse=order)
    for i in priorities:
        pkg = i[0].split(":")[0]
        if pkg in candidates:
            # popcon values go into the nine-digit range
            print("%9s %s" % ((i[vols], pkg)))


if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser(
        description=(
            "Filter the output of botch-calcportsmetric for "
            + '"build-attempted" packages from wanna-build'
        )
    )
    parser.add_argument(
        "-r",
        "--reverse",
        action="store_false",
        help="reverse the result of comparisons",
    )
    parser.add_argument(
        "candidates",
        metavar="build-attempt-list",
        type=read_build_attempted,
        help='output of "wanna-build -l build-attempted"',
    )
    parser.add_argument(
        "priorities",
        metavar="importance-metric",
        type=read_importance_metric,
        help="output of botch-calcportsmetric or from "
        + "http://bootstrap.debian.net/"
        + "importance_metric.html",
    )
    group = parser.add_mutually_exclusive_group()
    group.add_argument(
        "-m",
        "--min",
        action="store_true",
        help="sort by minimum number of blocked source " + "packages (default)",
    )
    group.add_argument(
        "-M",
        "--max",
        action="store_true",
        help="sort by maximum number of blocked source " + "packages",
    )
    group.add_argument(
        "--min-popcon",
        action="store_true",
        help="sort by minimum sum of popcon values of the " + "blocked source packages",
    )
    group.add_argument(
        "--max-popcon",
        action="store_true",
        help="sort by maximum sum of popcon values of the " + "blocked source packages",
    )
    parser.add_argument("-v", "--verbose", action="store_true", help="be verbose")
    args = parser.parse_args()
    # turn the selected option into the column number in the importance-metric
    # file if no option is set then the default is -m (the second column)
    try:
        vols = [args.min, args.max, args.min_popcon, args.max_popcon].index(True) + 1
    except ValueError:
        vols = 1
    main(args.candidates, args.priorities, args.reverse, vols)
