#!/bin/sh

# by Aleksey Cheusov <vle@gmx.net>

sysconfdir=/etc/dict

#####################################
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

internal_iconv (){
    iconv -c -f $1 -t $2
}

internal_recode (){
    recode -f $1..$2
}

internal_konwert (){
    konwert $1-$2
}

# for backward compatibility
if test "$DICTL_USE_ICONV"; then
    DICTL_USE=internal_iconv
elif test "$DICTL_USE_KONWERT"; then
    DICTL_USE=internal_konwert
elif test -z "$DICTL_USE"; then
    DICTL_USE=internal_recode
fi

#
charset2charset (){
    $DICTL_USE $1 $2
}

#####################################
echo apple |
   charset2charset $DICTL_SERVER_CHARSET $DICTL_CHARSET > /dev/null || \
{
    exit 1
}
echo apple |
   charset2charset $DICTL_CHARSET $DICTL_SERVER_CHARSET > /dev/null || \
{
    exit 1
}

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

shquote (){
    __cmd=`printf '%s\n' "$1" | sed "s|'|'\\\\\''|g"`
    printf "%s\n" "'$__cmd'"
}

cmd='dict'
while test $# -ne 0; do
    cmd="$cmd "`shquote "$1"`
    shift
done

cmd=$(printf '%s\n' "$cmd" | charset2charset $DICTL_CHARSET $DICTL_SERVER_CHARSET)

eval "$cmd" | charset2charset $DICTL_SERVER_CHARSET $DICTL_CHARSET
