#!/bin/rc

DEPS='BEGIN {
	target=""
	real = ARG
}
$0 ~ ARG {
	prereq = substr($1, 1, length($1) - 9)
	if (prereq != real) {
		target = target " " prereq
	}
}
END {
	print substr(target,2) ": " ARG
	print
}'

GRAPH='BEGIN {
	target=""
	real = ARG
	gsub ("\\/", "/", real)
	if (! (real in nodes)) {
		nodes[real] = ""
		node_real = real
		gsub("/", "_", node_real);
		gsub("\\.\\.", "up", node_real);
		print "\t" node_real " [label = \"" real "\"];"
	}
}
/ARG/ {
	prereq = substr($1, 1, length($1) - 9)
	node_prereq = prereq
	gsub("/", "_", node_prereq)
	gsub("\\.\\.", "up", node_prereq);
	if (! (prereq in nodes)) {
		nodes[prereq] = ""
		print "\t" node_prereq " [label = \"" prereq "\"];"
	}
	if (prereq != real) {
		print "\t" node_prereq " -> " node_real ";"
	}
}'

fn dirs {
	du . |
		grep -v '^\.$' |
		awk '{print $2}' |
		grep -v '(CVS|_obj|\.)$'
}

fn trim {
	sed -e s';^\./;;'
}

fn cond {
	sed -e s';^\./;;' -e s';/;\\/;g'
}

fn deps {
	awk 'BEGIN {
		target=""
		real = "'^$1^'"
		gsub ("\\/", "/", real)
	}
	/'^$1^'/ {
		prereq = substr($1, 1, length($1) - 9)
		if (prereq != real) {
			target = target " " prereq
		}
	}
	END {
		print substr(target,2) ": '^$1^'"
		print
	}' Make.deps
}

fn graph {
	awk 'BEGIN {
		target=""
		real = "'^$1^'"
		gsub ("\\/", "/", real)
		if (! (real in nodes)) {
			nodes[real] = ""
			node_real = real
			gsub("/", "_", node_real);
			gsub("\\.\\.", "up", node_real);
			print "\t" node_real " [label = \"" real "\"];"
		}
	}
	/'^$1^'/ {
		prereq = substr($1, 1, length($1) - 9)
		node_prereq = prereq
		gsub("/", "_", node_prereq)
		gsub("\\.\\.", "up", node_prereq);
		if (! (prereq in nodes)) {
			nodes[prereq] = ""
			print "\t" node_prereq " [label = \"" prereq "\"];"
		}
		if (prereq != real) {
			print "\t" node_prereq " -> " node_real ";"
		}
	}' Make.deps
}
dirs= `{dirs | trim}
dirpat= `{
	echo $dirs C |
		awk '{
			for(i = 1; i <= NF; i++) { 
				x = $i
				gsub ("/", "\\/", x)
				printf ("/^(%s)$/\n", x)
			}
		}'
}

~ $GOOS "" || GOOS = plan9
~ $GOARCH "" || GOARCH= 386

DEPS = `{pwd}^/mk.deps
echo 'install:V:	runtime
	mk packages
' >$DEPS
echo -n 'packages:V:	' >$DEPS.tmp
{
	for (dir in $dirs) @{
		top= `{pwd}
		cd $dir >/dev/null || exit no directory
		if (test -f mkfile) {
			sources= `{sed -n 's/^[ 	]*([^ 	]*\.go)[ 	]*\\*[ 	]*$/\1/p' mkfile}
			sources= `{echo $sources | sed 's/\$GOOS/'$GOOS'/g'}
			sources= `{echo $sources | sed 's/\$GOARCH/'$GOARCH'/g'}
			sources= `{ls $sources /dev/null >[2]/dev/null}
			deps= `{
				sed -n '/^[ 	]*import[ 	].*"/p; /^[ 	]*import[ 	]*\(/,/^[ 	]*\)[ 	]*$/p' $sources /dev/null |
					sed -n 's/^[^"]*"([^"]+)".*$/\1/p' |
					sort -u |
					grep -v '^'^$dir^'$'
			}
			echo -n $dir ' ' >>$DEPS.tmp
			if (! ~ $deps '') {
				echo $dir:V: $deps
			}
			if not {
				echo $dir:V:
			}
			echo '	echo ''*** building in ''^$target^'' ***'''
			echo '	cd $target'
			echo '	mk clean'
			echo '	mk'
			echo
		}
	}
} >>$DEPS

cat $DEPS.tmp >>$DEPS && rm $DEPS.tmp
