#!/bin/sh
#
# Termwrap detects the type of terminal that it is run on, and the language
# the user is using, and sets up the terminal for that language. This is
# useful for languages (e.g., Japanese) where a special program is needed
# to display that language at the console.
#
# Termwrap is used to run programs including base-config on the
# second-stage install.
#
# This is really something of a hack, since once termwrap is done the user
# still gets a standard login prompt and is no longer shielded by
# termwrap.

######################################################################
##	Set some environment variables.
######################################################################
# reads /etc/environment.
test -f /etc/environment && . /etc/environment

# Set all locale related environment variables.
LC_ALL=$LANG
export LANG LC_ALL

######################################################################
##	Display usage if no argument.
######################################################################
if [ -z "$1" ]; then
	echo "usage: $0 [-nnt] <command> [...]"
	echo "-nnt: don't run another terminal"
	exit 0
fi

######################################################################
##	Recognize terminal type.
######################################################################
case `/usr/bin/tty` in
/dev/tty|/dev/console|/dev/tty[1-9]*)
	TERMINAL=console
	;;
/dev/tty[p-za-e]*)
	TERMINAL=pseudo
	if [ ! -z "$DISPLAY" ]; then
		TERMINAL=x
	else
		case $TERM in
		rxvt|xterm*|kterm)	TERMINAL=x;;
		esac
	fi
	;;
/dev/tty[A-Z]*|/dev/cu*)
	TERMINAL=serial
	;;
esac

case $TERM in
dumb)	TERMINAL=dumb
esac

export TERMINAL

# Why don't we use dpkg-architecture? 
# Because it isn't in the base archive.

case $HOSTTYPE in 
i386)	/bin/grep -q 9800 /proc/version && SUBARCH=pc9800 ;;
esac

######################################################################
##	Select suitable terminal as wrapper.
######################################################################
WRAPPER=""

case $LANG in
ja*)	
	case $TERMINAL in
	x)
		#WRAPPER="/usr/X11R6/bin/kterm -e"
		WRAPPER="/usr/X11R6/bin/krxvt -e"
		;;
	console)
		if [ "$SUBARCH" != pc9800 -a "$TERMINAL" = console ]; then
			# Any platform except PC9800 require jfbterm
			# to display japanese fonts on console.
			WRAPPER="/usr/bin/jfbterm -e"
		fi
		;;
	# On pseudo and serial, we can't tell
	# if the terminal can display japanese fonts...
	esac
	;;
esac

if [ "$1" = "-nnt" ]; then
	WRAPPER=""
	shift
fi

######################################################################
##	Execute Wrapper.
######################################################################
if [ ! -z "$WRAPPER" -a -x "$WRAPPER" ]; then
	$WRAPPER /bin/true && exec $WRAPPER $@
fi

exec $@
