#!/bin/sh

# by Aleksey Cheusov <vle@gmx.net>

sysconfdir=/etc/dictd

#####################################
if test -z "$DICTL_SERVER_CHARSET"; then
    DICTL_SERVER_CHARSET=utf-8
fi

if test -z "$DICTL_CHARSET"; then
    if which locale >/dev/null 2>&1; then
	DICTL_CHARSET=`locale -k LC_CTYPE | sed -n 's/charmap="\(.*\)"/\1/p'`;
    fi

    if test -z "$DICTL_CHARSET"; then
	DICTL_CHARSET=C
    fi
fi

charset2charset (){
    if test "$DICTL_USE_ICONV"; then
	# `iconv --help' gives more options than `man iconv' (on my SuSE 9.0 system at least)
	# the -c makes iconv omit invalid characters from output
	iconv -c -f $1 -t $2//TRANSLIT
    elif test "$DICTL_USE_KONWERT"; then
	sedexpr='
		/(CP)?(437|8(5[0257]|6[0-69]|74))/	{ s//cp\2/; q }
		/8859_([1-9])/				{ s//iso\1/; q }
		/ANSI_X3.4(-19(68|86))?/		{ s//ascii/; q }
		/(US-)?ASCII/				{ s//ascii/; q }
		/(CP|WINDOWS-)(125[0-8])/		{ s//cp\1/; q }
		/ISO([-_]?8859-|8859)([1-9]|1[01345])/	{ s//iso\2/; q }
		/KOI8-?R/				{ s//koi8r/; q }
		/KOI8-?U/				{ s//koi8u/; q }
		/UTF-?8/				{ s//utf8/; q }
		/VISCII/				{ s//viscii/; q }
		/.*/					{ s///; q }'
	from=`echo "$1" | tr a-z A-Z | sed -r -e "$sedexpr"`
	to=`echo "$2" | tr a-z A-Z | sed -r -e "$sedexpr"`
	konwert "$from-$to"
    else
	recode -f $1..$2
    fi
}

#####################################

if
    test "_$DICTL_CHARSET" = "_C" ||
    test "_$DICTL_CHARSET" = "_POSIX"
then
    echo "iconv/recode/konwert do not support coversions to/from locale \"$DICTL_CHARSET\""
    exit 1
fi

if
    test "_$DICTL_SERVER_CHARSET" = "_C" ||
    test "_$DICTL_SERVER_CHARSET" = "_POSIX"
then
    echo "iconv/recode/konwert do not support coversions to/from locale \"$DICTL_SERVER_CHARSET\""
    exit 1
fi

if test "$DICTL_USE_ICONV"; then
    if ! which iconv >/dev/null 2>&1; then
	echo "'iconv' is not available. See dictl(1) for help." 1>&2
	exit 2
    fi
elif test "$DICTL_USE_KONWERT"; then
    if ! which konwert >/dev/null 2>&1; then
	echo "'konwert' is not available. See dictl(1) for help." 1>&2
	exit 2
    fi
else
    if ! which recode >/dev/null 2>&1; then
	echo "'recode' is not available. See dictl(1) for help." 1>&2
	exit 2
    fi
fi

#####################################

params="dict"

while test $# -ne 0; do
    case $1 in
	--run-a-pipe)
	    charset2charset $DICTL_SERVER_CHARSET $DICTL_CHARSET
	    exit $?;;
	*)
	    p=`echo "$1" |
		charset2charset $DICTL_CHARSET $DICTL_SERVER_CHARSET |
		sed "s/'/'\"'\"'/g"`

	    params="$params '$p'"

	    # ...to be compatible with dict
	    if echo $1 |
		awk '{
		    exit ($0 !~ /^(-L|--license|-V|--version|--help)$/)
		}'
	    then
		break
	    fi;;
    esac

    shift
done

eval $params -P - | $0 --run-a-pipe
