#!/bin/sh
# $Id$ 

# Written by Cherry G. Mathew. <cherry@zyx.in>
# Recursively walk dependant directories, and run 
# the install() function (see below)

# This script came in really handy, when I basically did 
# rm -rf /var/db/pkg; with a pre-built pkgsrc directory 
# on hand. 
# This script helps run '# make reinstall' in all 
# dependendant packages. Quite handy, when all of them
# are built, but not installed. 


usage()
{
    echo usage: instdep pathto/category/package && exit
}

# Parameter sanity
checkparams()
{
    [ ! -z ${2-} ] && usage
}

# return all package deps, one per line
# This is an expensive operation. Use sparingly!

showdeps()
{
    checkparams ${*}

    local _pkgdir=${1}
    (cd $_pkgdir && make show-depends-pkgpaths)
}

isleaf()
{
    local _pkgdir=${1};
    [ -z $_pkgdir ] && return 0
    return 1;
}

install()
{
    checkparams ${*}

    local _package=${1}
    pkg_info -K /usr/pkg/dbdir $(basename $_package) > /dev/null && echo skipping installed package $_package && return
    (cd $_package && make reinstall && make package)
}

traverse()
{
	local _pkgdir=${1}
	local _pkgdeps="$(showdeps $_pkgdir)"

	checkparams ${*}

	echo traversing $_pkgdir

	if isleaf $_pkgdeps; then
		echo $_pkgdir is a leaf
		install $_pkgdir
		return
	else
		echo $_pkgdir is not a leaf
		echo walking $_pkgdeps
		for _pkg in $_pkgdeps;
		do 
		    echo stepping into $_pkg; 
		    traverse "$_pkg"; 
		    echo "returned to $_pkgdir"
		    install $_pkgdir
		done;
		return
	fi

}

checkparams ${*}
traverse ${1}
