#!/bin/sh
#
# Install dict, dictd, and dict-de-en and check that german-english
# and english-german dictionaries are available.
#
# (c) 2018 Roland Rosenfeld <roland@debian.org>

VERSION=$(dpkg-parsechangelog | sed -rne 's/^Version: ([0-9.]+)[-+].*$/\1/p')

if [ -z "$AUTOPKGTEST_TMP" ]; then
    AUTOPKGTEST_TMP=$(mktemp -d)
fi

trap 'rm -rf $AUTOPKGTEST_TMP' EXIT

PORT=2629
DICTDCONF=$AUTOPKGTEST_TMP/dictd.conf
DICTCONF=$AUTOPKGTEST_TMP/dict.conf
DICTDPID=$AUTOPKGTEST_TMP/dictd.pid

cat <<EOF > "$DICTDCONF"
global {
listen_to 127.0.0.1
port $PORT
pid_file $DICTDPID
}
access {
allow localhost
allow 127.0.0.1
}
include /var/lib/dictd/db.list
EOF

cat <<EOF > "$DICTCONF"
server localhost { port $PORT }
EOF

/usr/sbin/dictd -c "$DICTDCONF"
trap 'kill $(cat "$DICTDPID"); rm -rf $AUTOPKGTEST_TMP' EXIT

sleep 1 # wait until dictd is started up


EXIT=0

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

DICTD=0

OUTPUT=$AUTOPKGTEST_TMP/dict-D.out
dict -c "$DICTCONF" -D > "$OUTPUT"

if ! grep -q "german-english German - English Dictionary $VERSION" "$OUTPUT"
then
    echo "missing: german-english German - English Dictionary $VERSION"
    EXIT=1
    DICTD=1
fi

if ! grep -q "english-german English - German Dictionary $VERSION" "$OUTPUT"
then
    echo "missing: english-german English - German Dictionary $VERSION"
    EXIT=1
    DICTD=1
fi

if [ "$DICTD" = 0 ]
then
    echo "PASS: english-german and german-english dictd dictionaries found"
else 
    echo "found:"
    cat "$OUTPUT"
fi

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

DE_EN=0

OUTPUT=$AUTOPKGTEST_TMP/dict-de-en.out
dict -c "$DICTCONF" -d german-english Straße -C > "$OUTPUT"

if ! grep -q "street" "$OUTPUT"
then
    echo "lookup Straße => missing: street"
    DE_EN=1
    EXIT=1
fi

if ! grep -q "road" "$OUTPUT"
then
    echo "lookup Straße => missing: road"
    DE_EN=1
    EXIT=1
fi

if [ "$DE_EN" = 0 ]
then
    echo "PASS: translation from Straße to street/road found"
else
    echo "found:"
    cat "$OUTPUT"
fi

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

EN_DE=0

OUTPUT=$AUTOPKGTEST_TMP/dict-de-en.out
dict -c "$DICTCONF" -d english-german bowl -C > "$OUTPUT"

if ! grep -q "Schüssel" "$OUTPUT"
then
    echo "lookup bowl => missing: Schüssel"
    EN_DE=1
    EXIT=1
fi

if ! grep -q "kegeln" "$OUTPUT"
then
    echo "lookup bowl => missing: kegeln"
    EN_DE=1
    EXIT=1
fi

if [ "$EN_DE" = 0 ]
then
    echo "PASS: translation from bowl to Schüssel/kegeln found"
else
    echo "found:"
    cat "$OUTPUT"
fi

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

exit $EXIT
