#! /bin/sh
#
# Make sure we're really running bash.
#
# I would really have preferred to write this script in a language with
# better string handling, but alas, bash is the only scripting language
# that I can be reasonable sure everybody has on their Linux machine.
#

CONFIG=config.h


[ -z "$BASH" ] && { echo "Configure requires bash" 1>&2; exit 1; }

# Disable filename globbing once and for all.
# Enable function cacheing.
set -f -h

#
# readln reads a line into $ans.
#
#	readln prompt default
#
function readln()
{
  echo -n "$1"
  IFS='@' read ans </dev/tty || exit 1
  [ -z "$ans" ] && ans=$2
}

# bool processes a boolean argument
#
#	bool tail
#
function bool()
{
  # Slimier hack to get bash to rescan a line.
  eval "set -- $1"
  ans=""
  while [ "$ans" != "y" -a "$ans" != "n" ]
  do
	readln "$1 ($2) [$3] " "$3"
  done
  if [ "$ans" = "y" ]; then
	echo "#define $2 1" >>${CONFIG}
    else
	echo "#define $2 0" >>${CONFIG}
  fi
  raw_input_line="bool '$1' $2 $ans"
  eval "$2=$ans"
}

# int processes an integer argument
#
#	int tail
#
function int()
{
  # Slimier hack to get bash to rescan a line.
  eval "set -- $1"
  ans="x"
  while [ $[$ans+0] != "$ans" ];
  do
	readln "$1 ($2) [$3] " "$3"
  done
  echo "#define $2 ($ans)" >>${CONFIG}
  raw_input_line="int '$1' $2 $ans"
  eval "$2=$ans"
}

  #
  # Make sure we start out with a clean slate.
  #
  > config.new
  echo "/*" > ${CONFIG}
  echo " * Automatically generated by Configure - don't edit" >> ${CONFIG}
  echo " */" >> ${CONFIG}

  stack=''
  branch='t'

  while IFS='@' read raw_input_line
  do
	# Slimy hack to get bash to rescan a line.
	read cmd rest <<-END_OF_COMMAND
		$raw_input_line
	END_OF_COMMAND

	if [ "$cmd" = "*" ]; then
		if [ "$branch" = "t" ]; then
			echo "$raw_input_line"
			echo "# $rest" >>$CONFIG
			if [ "$prevcmd" != "*" ]; then
				echo >>${CONFIG}
				echo "/* $rest" >>${CONFIG}
			else
				echo " * $rest" >>${CONFIG}
			fi
			prevcmd="*"
		fi
	else
		[ "$prevcmd" = "*" ] && echo " */" >>${CONFIG}
		prevcmd=""
		case "$cmd" in
		:)	[ "$branch" = "t" ] && echo "$raw_input_line" ;;
		int)	[ "$branch" = "t" ] && int "$rest" ;;
		bool)	[ "$branch" = "t" ] && bool "$rest" ;;
		exec)	[ "$branch" = "t" ] && ( sh -c "$rest" ) ;;
		if)	stack="$branch $stack"
			if [ "$branch" = "t" ] && eval "$rest"; then
				branch=t
			else
				branch=f
			fi ;;
		else)	if [ "$branch" = "t" ]; then
				branch=f
			else
				read branch rest <<-END_OF_STACK
					$stack
				END_OF_STACK
			fi ;;
		fi)	[ -z "$stack" ] && echo "Error!  Extra fi." 1>&2
			read branch stack <<-END_OF_STACK
				$stack
			END_OF_STACK
			;;
		esac
	fi
	echo "$raw_input_line" >>config.new
  done
  [ "$prevcmd" = "*" ] && echo " */" >>${CONFIG}

  [ -z "$stack" ] || echo "Error!  Untermiated if." 1>&2

  mv config.new config.status
  exit 0
