#!/bin/sh
# --- T2-COPYRIGHT-NOTE-BEGIN ---
# This copyright note is auto-generated by ./scripts/Create-CopyPatch.
# 
# T2 SDE: misc/archive/showdeps.sh
# Copyright (C) 2004 - 2005 The T2 SDE Project
# 
# More information can be found in the files COPYING and README.
# 
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License. A copy of the
# GNU General Public License can be found in the file COPYING.
# --- T2-COPYRIGHT-NOTE-END ---

root=

usage() {
	cat <<EOT
usage: $0 [-root <root>] [<pkg>]+
EOT
}

getdeps() {
	if [ -f package/*/$1/$1.cache ]; then
		grep -e "^\[DEP\]" package/*/$1/$1.cache | cut -d' ' -f2- | tr '\n' ' '
	else
		echo "unknown"
	fi
}
getprio() {
	local prio=
	if [ -f package/*/$1/$1.desc ]; then
		prio=`sed -n -e "s,^\[P\] . .* \(.*\),\1,p" package/*/$1/$1.desc`
	fi

	[ -n "$prio" ] && echo "$prio" || echo "---.---"
}
pkginstalled() {
	[ -f $root/var/adm/packages/$1 ]
}

digdeps() {
	local deep="$1" pkg="$2" prefix="$3"
	local cache="$4" banner= dep=

	[ $deep -eq 0 ] && return 0
	(( deep-- ))

	banner="$pkg($( getprio $pkg ))"

	if pkginstalled $pkg; then
		banner="$banner+"
	else
		banner="$banner-"
	fi

	echo -e "$prefix$banner"
	for dep in $( getdeps $pkg ); do
		if [ "$dep" == "unknown" ]; then
			echo -e "$prefix$banner\tNODEPS"
		elif [ -z "$(echo "$cache" | grep ":$dep:" )" ]; then
			digdeps $deep $dep "$prefix$banner\t" "$cache$pkg:"
		fi
	done
}

while [ $# -ne 0 ]; do
	case "$1" in
		-root)	root=$2
			shift ;;
		-*)	echo "ERROR: Option $1 is not recognized."
			usage; exit 1	;;
		*)
			break;
	esac
	shift
done

for pkg; do
	if [ -f package/*/$pkg/$pkg.desc ]; then
		digdeps 2 $pkg '' ':'
	else
		echo "ERROR: '$pkg' not found!" 1>&2
	fi
done
