#!/bin/bash

unset LANG LC_ALL
[ -e /etc/repoman.conf ] && . /etc/repoman.conf
[ -e ~/.repoman.conf ] && . ~/.repoman.conf

_go_getroot ()
{
    echo $fst_root/$tree
}
go ()
{
    cd `_go_getroot`;
    cd `find source -type d -name $1`
}
die()
{
	echo $*
	exit 1
}

id=$1
shift

if [ -z "$id" ]; then
	man revdep-rebuild
	exit $?
fi

tree=$repos
if [ "$1" == "-t" ]; then
	tree=$2
	shift 2
fi

method="Exact"
if [ "$1" == "--other" ]; then
	method="Other"
	shift
fi

nobuild=
if [ "$1" == "--nobuild" ]; then
	shift
	nobuild="--nobuild"
fi

push=
if [ "$1" != "--nopush" ]; then
	push="--push"
else
	shift
fi

sed=
if [ "$1" == "--sed" ]; then
	sed="$2"
	shift 2
fi

pkg=$(lynx -dump http://frugalware.org/packages/$id |grep 'Name:'|sed 's/.*]//')
ver=$(lynx -dump http://frugalware.org/packages/$id |grep 'Version:'|sed 's/.*Version: //')
revdeps=$(lynx -source -dump http://frugalware.org/packages/$id|grep "$method reverse depends:"|sed 's|<a href="[^"]*">\([^<]*\)</a>|\1|g;s|.*<td>\(.*\)</td>.*|\1|')
count=$(echo $revdeps|sed 's/ /\n/g'|wc -l)

echo "Rebuilding $count packages in -$tree for $pkg-$ver"
echo
echo "Targets: $revdeps"
echo "Press ENTER to continue"
read junk

log=`mktemp`
for i in $revdeps
do
	go ${i%%_module*}
	[ -n "$sed" ] && sed -i "$sed" FrugalBuild
	bumppkg -t $tree --rebuild $nobuild "- rebuild with $pkg-$ver" $push || echo $i >>$log
done
cat $log
rm $log
