#!/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.
######################################################################
# If the LANG variable already is set, ignore /root/dbootstrap_settings
# (from the boot floppies). This would make this work when invoked
# manually with LANG set, even if /root/dbootstrap_settings exists.
if [ -z "$LANG" ]; then
	DI_DB=/var/log/debian-installer/cdebconf/questions.dat
	if [ -e $DI_DB ]; then
		# Pull LANG out of the d-i cdebconf database.
		LANG=$(debconf-copydb d-i stdout \
				-c Name:d-i -c Driver:File -c Filename:$DI_DB \
				-c Name:stdout -c Driver:Pipe -c InFd:none \
				--pattern='^debian-installer/locale$' |
		       grep ^Value: | cut -d ' ' -f 2)
	elif [ -e /root/dbootstrap_settings ]; then
		# Set LANG, so debconf uses the installation locale.
	        . /root/dbootstrap_settings || true
	fi
	if [ ! -z "$LANG" ]; then
		export LANG
	fi
fi

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

######################################################################
##	Some functions
######################################################################
info() {
	echo "info: $@"
}
warning() {
	echo "warning: $@"
}
error() {
	echo "error: $@"
}

unset_lang_language() {
	# The requested charset is not supported.  Do not use the
	# given locale.	 If it was used, the translated texts might be
	# completely unreadable in the current terminal

	if [ "$LANG" ] ; then
		warning "Disabling unsupported locale '$LANG'."
		unset LANG
	fi
	if [ "$LANGUAGE" ] ; then
		warning "Disabling unsupported language list '$LANGUAGE'."
		unset LANGUAGE
	fi
}

try_load_charset() {
	ENCODING=$1
	ACM=$2
	
	# Load character map into the console
	# ACM name is from /usr/share/consoletrans/$ACM.acm.gz
	case $TERMINAL in
	    console)
		info "Switching console charset mapping to $ENCODING"
		charset G0 $ACM
		# Hm, should it update /etc/console-tools/config as well?
		;;
	    *)
		error "Unable to switch charset mapping to $ENCODING"
		unset_lang_language
		;;
	esac
}

######################################################################
##	Generate the locale data files if missing
######################################################################

# Use LANG_INST and LANGUAGE_INST from first stage installer if
# set and allow override with LANG and LANGUAGE from /etc/environemnt.

# Keep the locale info in the _INST variables until they are verified.
if [ "$LANG" ]; then
    LANG_INST=$LANG
    unset LANG
fi
if [ "$LANGUAGE" ]; then
    LANGUAGE_INST=$LANGUAGE
    unset LANGUAGE
fi

if [ "$LANG_INST" ]; then
    localeconf=/etc/locale.gen
    tmpfile=`/bin/tempfile`

    # Use this to detect if the 'locales' package is installed
    localegen=`which locale-gen`

    validlocale $LANG_INST 2> /dev/null > $tmpfile || true
    read locale charset < $tmpfile || true
    rm -f $tmpfile
    unset tmpfile

    if validlocale $LANG_INST > /dev/null 2>&1; then
	# Valid locale, no need to generate it
	true
    else
	# Hm, should we install the 'locales' package if it is missing?
	if [ "$localegen" -a -x $localegen ]; then
	    echo "$locale $charset" >> $localeconf
	    $localegen | sed 's/^/termwrap: locale-gen: /' || true
	else
	    warning "Package 'locales' not installed.  Unable to generate $LANG"
	fi
    fi

    # Make sure the locale is valid
    if validlocale $LANG_INST > /dev/null 2>&1 ; then
	if [ "$LANGUAGE_INST" ]; then
	    LANGUAGE=$LANGUAGE_INST
	    export LANGUAGE
	    unset LANGUAGE_INST
	fi
	LANG=$LANG_INST
	LC_ALL=$LANG_INST
	export LANG LC_ALL
	unset LANG_INST
    else
	unset LANG_INST
	unset LANGUAGE_INST
    fi
    unset locale
    unset charset
    unset localeconf
    unset localegen
fi

######################################################################
##	Recognize terminal type.
######################################################################
case `/usr/bin/tty` in
/dev/console)
	# Use fgconsole to detect if it is a serial console.
	if type fgconsole >/dev/null && [ serial = `fgconsole` ] ; then
		TERMINAL=serial
	else
		TERMINAL=console
	fi

	# Or try another way, copied from d-i udeb rootskel.
	#case `readlink /proc/self/fd/0` in
	#        /dev/console)
	#		TERMINAL=serial
	#		;;
	#	*)
	#		TERMINAL=console
	#		;;
	#esac

	;;
/dev/tty|/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

# If the default linux kernel TERM setting is used for serial consoles, change
# it to vt100.  This assume serial consoles understand vt100.  Almost
# all terminal programs can handle vt100.
if [ serial = "$TERMINAL" -a linux = "$TERM" ] ; then
	TERM=vt100
fi

case $TERM in
dumb)	TERMINAL=dumb
esac

export TERMINAL

case $(dpkg --print-installation-architecture) in 
i386)	/bin/grep -q 9800 /proc/version && SUBARCH=pc9800 ;;
esac

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

# For this to work, the current locale must be valid.  The block
# generating the locale should have taken care of that.  If it isn't
# valid, the output is 'ANSI_X3.4-1968' (at least on my test machine
# 2002-02-09), and the case test below should unset both LANG and
# LOCALE
ENCODING=$(locale charmap)

case $ENCODING in
ISO-8859-1)
	# Supported by Linux console and xterm by default
	;;
ISO-8859-2)
	# Load ISO-8859-2 charset mapping into console
	try_load_charset "$ENCODING" iso02
	;;
ISO-8859-13)
	# Load ISO-8859-13 charset mapping into console (Require
	# patch from #205744).
	try_load_charset "$ENCODING" iso13
	;;
ISO-8895-15)
	# Load ISO-8859-15 charset mapping into console
        try_load_charset "$ENCODING" iso15
	;;
eucJP|EUC-JP|ujis)
	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 -c other,EUC-JP,iconv.UTF-8 -e"
		fi
		;;
	# On pseudo and serial, we can't tell
	# if the terminal can display japanese fonts...
	esac
	;;
UTF-8)
	# Enable UTF-8 in console
	if [ "$TERMINAL" = console ] ; then
		# An alternative is bogl-bterm, to support more then
		# 512 glyphs.
		echo -ne "\033%G"
	else
		warning "Unable to enable UTF-8 encoding, not in Linux console."
		unset_lang_language
	fi
	;;
*)
	warning "Current charset encoding '$ENCODING' is unknown.  Using default terminal."
	unset_lang_language
esac

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

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

$@

case $ENCODING in
ISO-8859-1)
	# Nothing to do, using default config
	;;
ISO-8859-2)
	# Unload ISO-8859-2 charset mapping, by loading ISO-8859-1 instead
	try_load_charset "$ENCODING" iso01
	;;
ISO-8859-13)
	# Unload ISO-8859-13 charset mapping, by loading ISO-8859-1 instead
	try_load_charset "$ENCODING" iso01
	;;
ISO-8895-15)
	# Unload ISO-8859-15 charset mapping, by loading ISO-8859-1 instead
	try_load_charset "$ENCODING" iso01
	;;
eucJP|EUC-JP|ujis)
	# Nothing to do, using wrapper
	error "Should never end up here when using '$ENCODING'"
	;;
UTF-8)
	# Disable UTF-8 in console
	if [ "$TERM" = console ] ; then
		echo -ne "\033%@"
	else
		: # Nothing to do
	fi
	;;
*)
	# Nothing to do
	;;
esac
