#!/bin/bash
#Copyright 2003 William Stearns <wstearns@pobox.com>
#Released under the GPL
#Many thanks to all the Netfilter team for their great work.
#Version 0.1

if [ -z "$1" ]; then
	echo 'Usage:'
	echo -e "\t$0 pompatch1.patch [pompatch2.patch]..."
	echo
	echo This converts the associated .config.in and
	echo .configure.help files over to pom patches for
	echo the 2.6 kernel\'s Kconfig files.  The results
	echo may need a bit of manual tweaking.
	echo Assume this program will wipe out and replace any
	echo .patch.Kconfig files in the current directory.
	echo Exiting.
	exit 1
fi

debug () {
	:
	#echo "$*" >&2
}

DropFirstLine () {
	read ALine
	while read ALine ; do
		echo "$ALine"
	done
}

ParseCILine () {
	#echo Y${*}Y
	#The first object on the line is the option type.
	case "$1" in
	dep_tristate)
		Type="tristate"
		;;
	tristate)
		Type="tristate"
		;;
	bool)
		Type="bool"
		;;
	*)
		echo "Unknown config.in line type: X${1}X"
		#echo Exiting
		#exit 1
		;;
	esac
	shift

	#Now, we keep grabbing words until we get to CONFIG_ or $CONFIG_
	#(which are the option names and dependencies)
	DescString=''
	OptionName=''
	Depends=''
	while [ -n "$1" ]; do
		case "$1" in
		CONFIG_*|\$CONFIG_*)
			if [ -z "$OptionName" ]; then
				OptionName="`echo $1 | sed -e 's/^CONFIG_//' -e 's/^$CONFIG_//'`"
			else
				if [ -z "$Depends" ]; then
					Depends="`echo $1 | sed -e 's/^CONFIG_//' -e 's/^$CONFIG_//'`"
				else
					Depends="$Depends && `echo $1 | sed -e 's/^CONFIG_//' -e 's/^$CONFIG_//'`"
				fi
			fi
			;;
		*)
			DescString="$DescString $1"
			;;
		esac
		shift
	done
	#echo -e "Type $Type\tOptionName $OptionName\tDepends $Depends\tDesc $DescString"

	echo "config $OptionName"
	echo -e "\t$Type $DescString"
	if [ -n "$Depends" ]; then
		echo -e "\tdepends on $Depends"
	fi
}


for OnePatch in $* ; do
	if [ -f "$OnePatch.config.in" ]; then
		debug "$OnePatch has config.in, good"

		rm -f $OnePatch.Kconfig

		#Grab each of the tristate/bool lines from the 2.4 .config.in
		#files and convert them over to Kconfig blocks.
		for OneCI in $OnePatch.config.in* ; do
			if [ "`cat $OneCI | DropFirstLine | egrep '(^\W*if|^\W*fi|^\W*define_tristate|^\W*else|^\W*#)' | wc -l`" -gt 0 ]; then
				echo "Warning: $OneCI has other lines, please merge these by hand" >&2
				cat $OneCI | DropFirstLine | egrep '(^\W*if|^\W*fi|^\W*define_tristate|^\W*else|^\W*#)' | sed -e 's/^/        /' >&2
			fi

			cat $OneCI | \
			 DropFirstLine | \
			 grep -v '^\W*if ' | \
			 grep -v '^\W*fi' | \
			 grep -v '^\W*define_tristate' | \
			 grep -v '^\W*else' | \
			 sed -e 's/#.*//' | \
			 grep -v '^\W*$' | \
			 ( while read ALine ; do
				ParseCILine $ALine
			 done ) >>$OnePatch.Kconfig
		done

	else
		if [ -f "$OnePatch.configure.help" ]; then
			echo "$OnePatch has no config.in, but it has a configure.help.  What do I do?  Skipping" >&2
		else
			debug "$OnePatch has no config.in or configure.help, skipping"
		fi
	fi
done




