#! /bin/sh
#
# Configure.sh  for  man-pages-ja-0.4  1998-11-30
#
# this script base on Configure.sh of net-tools-1.41
#

CONFIG_MK="config.tmp"
CONFIG_MN="config.man"
CONFIG_LG="config.log"
CONFIG_ST="config.status"

[ -z "$BASH" ] && { echo "Config script needs BASH" 1>&2; exit 1; }
set -f -h

function readln()
{
	echo -n "$1 "
	IFS='!' read answer < /dev/tty
	[ -z "$answer" ] && answer=$2
}

function ask_string()
{
	eval "set -- $1"
	readln "$1 ($2) [$3]" "$3"
	eval "$2=$answer"
	echo "$2=$answer" >> $CONFIG_MK
	echo "string '$1' $2 $answer" >> $CONFIG_LG
}

function ask_bool()
{
	eval "set -- $1"
	while :; do
		readln "$1 ($2) [$3]" "$3"
		case "$answer" in
		[yY] | [yY]es | YES)
			answer=y
			break;;
		[nN] | [nN][oO])
			answer=n
			break;;
		*)
			echo "select bool value (y/n) !!"
			;;
		esac
	done
	eval "$2=$answer"
	echo "$2=$answer" >> $CONFIG_MK
	echo "bool '$1' $2 $answer" >> $CONFIG_LG
}

function ex_comm()
{
	echo $raw
	echo $raw >> $CONFIG_MK
	echo $raw >> $CONFIG_LG
}

function ex_eval()
{
	eval $1 >> $CONFIG_MK
	echo $raw >> $CONFIG_LG
}

function ex_define()
{
	eval "set -- $1"
	eval "$1=$2"
	echo "$1=$2" >> $CONFIG_MK
	echo  $raw >> $CONFIG_LG
}

> $CONFIG_LG
> $CONFIG_MK

function ex_if()
{
	stack="$mode $exmode $stat $stack"
	exmode=$mode
	if [ "$exmode" = "t" ] && eval "$rest"; then
		mode=t
	else
		mode=f
	fi
	stat=t
	echo $raw >> $CONFIG_LG
}

function ex_else()
{
	if [ "$stat" = "t" ]; then
		if [ "$mode" = "f" -a "$exmode" = "t" ]; then
			mode=t
		else
			mode=f
		fi
	else
		echo "script eorror (ELSE nesting) $stat:$stack" 1>&2
		exit 1;
	fi
	stat=e
	echo $raw >> $CONFIG_LG
}

function ex_fi()
{
	if [ "$stat" = "none" ]; then
		echo "script error (FI nesting)" 1>&2
		exit 1;
	fi
	read mode exmode stat stack <<-END_OF_STACK
		$stack
	END_OF_STACK
	echo $raw >> $CONFIG_LG
}

function nothing()
{
	echo $raw >> $CONFIG_LG
}

mode=t
exmode=t
stat=none
stack=""
while IFS='!' read raw
do
	read cmd rest <<-END_OF_COMMAND
		$raw
	END_OF_COMMAND

	if [ "$mode" = "t" ]; then
		case "$cmd" in
		\#)	ex_comm		"$rest";;
		string)	ask_string	"$rest";;
		bool)	ask_bool	"$rest";;
		eval)   ex_eval		"$rest";;
		define) ex_define	"$rest";;
		if)	ex_if		"$rest";;
		else)	ex_else		"$rest";;
		fi)	ex_fi		"$rest";;
		esac
	else
		case "$cmd" in
		\#)	nothing		"$rest";;
		string)	nothing		"$rest";;
		bool)	nothing		"$rest";;
		eval)   nothing		"$rest";;
		define) nothing		"$rest";;
		if)	ex_if		"$rest";;
		else)	ex_else		"$rest";;
		fi)	ex_fi		"$rest";;
		esac
	fi
done

mv -f $CONFIG_LG $CONFIG_ST
mv -f $CONFIG_MK $CONFIG_MN
exit 0
