#!/bin/sh
#
# ----------------------------------------------------------------------------
# "THE BEER-WARE LICENSE" (Revision 42):
# <beat@chruetertee.ch> wrote this file. As long as you retain this notice you
# can do whatever you want with this stuff. If we meet some day, and you think
# this stuff is worth it, you can buy me a beer in return Beat Gaetzi
# ----------------------------------------------------------------------------
#

trap 'rm -f /tmp/portsdep_$$; exit 1' 1 2 15

VERSION=1.5

usage () {
	echo ''
	echo "portsopt version ${VERSION}"
	echo ''
	echo 'Usage:'
	echo ''
	echo 'Run portsopt in a directory with a ports Makefile'
	echo ''
	echo 'Options:'
	echo '-c Call make config. If -r is set too, make config-recursive will be called'
	echo '-r Show (WITH*|PORT_OPTIONS) knobs also from the port dependencies'
	echo '-h Display this help'
	exit 0
}

RECURSIVE=no
CONFIG=no

while getopts 'chr' COMMAND_LINE_ARGUMENT ; do
	case "${COMMAND_LINE_ARGUMENT}" in
		c)		CONFIG=yes ;;
		h)      usage 0 ;;
		r)      RECURSIVE=yes ;;
		*)      usage ;;
	esac
done

search () {
	egrep -v '^#|IGNORE_WITH|BROKEN_WITH|CONFIGURE_ENV|.error|.endif|.undef' | sed 's/&&/\
	/g;s/||/\
	/g;s/\\//g;s/\!//g;s/\#//g;s/.elif defined//g;s/.if defined//g;s/.ifdef//g;s/defined//g;s/(//g;s/)//g;s/	//g;s/^\.//g;s/else//g;s/if//g;s/DEPENDS_ARGS+=//g;s/OPT_NAME=//g;s/ndef//g' | sed 's/^ *//g;s/ $//g' | sed 's/ $//g' | egrep -v 'PLIST|{|}' | sort -u
}

if [ -e Makefile ] ;
then
	if [ ${CONFIG} = yes ] ;
	then
		if [ ${RECURSIVE} = yes ] ;
		then
			make config-recursive
			clear
		else
			make config	
			clear
		fi
	fi
	echo `pwd`
	make showconfig
	egrep '(WITH|PORT_OPTIONS)' Makefile | search
	for j in `find . -name "Makefile.*" | grep -v files`
	do
			egrep '(WITH|PORT_OPTIONS)' ${j} | search
	done
else
	echo Makefile not found
	exit 1
fi

if [ ${RECURSIVE} = yes ] ;
then
	make all-depends-list > /tmp/portsdep_$$
	for i in $(cut -d: -f1 /tmp/portsdep_$$); 
	do 
		echo "--------------------"
		echo ${i} 
		cd ${i}
		make showconfig
		egrep '(WITH|PORT_OPTIONS)' Makefile | search
		for j in `find . -name "Makefile.*" | grep -v files`
		do
			egrep '(WITH|PORT_OPTIONS)' ${j} | search
		done
	done
	rm -f /tmp/portsdep_$$
fi
