#!/bin/bash

# Given an APT list as input, output a table mapping (binary) package
# names to the number of direct links in the dependency graph they
# entail.

# by Zack

# Requirements: a dctrl-tools version supporting --whole-pkg as per
# patch of #476861. Source code at
# http://git.upsilon.cc/cgi-bin/gitweb.cgi?p=dctrl-tools.git;a=summary
# (or ask Zack :))

# Field names which are considered as good links. Comma separated.
# RELS="depends,pre-depends,conflicts,breaks"
RELS="depends,pre-depends"

die_usage () {
    echo "Usage: compute-direct-impact APT_LIST"
    exit 2
}

# shorten an APT list, by restricting only to the interesting fields
# (according to $RELS above). Return a temporary file name of the new
# list, which should be removed by the caller.
filter_apt_list () {
    apt_tmp=`mktemp -t`
    if echo "$1" | grep -q "\.bz2$" ; then
	bzcat "$1" | grep-dctrl -F $RELS,package -s $RELS,package '' > $apt_tmp
    elif echo "$1" | grep -q "\.gz$" ; then
	zcat "$1" | grep-dctrl -F $RELS,package -s $RELS,package '' > $apt_tmp
    else
	grep-dctrl -F $RELS,package -s $RELS,package '' "$1" > $apt_tmp
    fi
    echo "$apt_tmp"
}

test -z "$1" && die_usage
apt_list="$1"

apt_list=$(filter_apt_list $apt_list)
trap "rm -f $apt_list" EXIT

pkgs=$(grep -i '^package:' "$apt_list" | cut -f 2 -d' ' | sort -u)
for pkg in $pkgs ; do 
    related=$(grep-dctrl -F "$RELS" -s package -n --whole-pkg "$pkg" "$apt_list")
    related_no=$(for rel in $related ; do echo $rel ; done| wc -w)
    echo -e "$pkg\t$related_no"
done
