#!/bin/sh

set -e

SDCV="$1"
TEST_DIR="$2"
TMP_DIR=$(mktemp -d)
trap 'rm -rf "$TMP_DIR"' EXIT INT QUIT TERM

unset SDCV_PAGER
unset STARDICT_DATA_DIR
XDG_CACHE_HOME="$TMP_DIR/cache"
export XDG_CACHE_HOME

# The same dictionary basename occurs in two directories, but their synonym
# entries have different lengths and therefore require different offsets.
for name in first second; do
    dict_dir="$TMP_DIR/$name"
    mkdir "$dict_dir"
    for ext in ifo idx dict.dz syn; do
        cp "$TEST_DIR/stardict-test_synonyms-2.4.2/test.$ext" "$dict_dir/test.$ext"
    done
    # A directory at each sibling cache path forces use of the user cache.
    mkdir "$dict_dir/test.idx.oft" "$dict_dir/test.syn.oft"
done
printf 'a\000\000\000\000\000zzzzz\000\000\000\000\000' > "$TMP_DIR/second/test.syn"

lookup() {
    if ! result=$("$SDCV" -x -n --data-dir "$TMP_DIR/$1" -u "Test synonyms" "$2"); then
        echo "lookup of $2 in $1 failed"
        exit 1
    fi
    if ! printf '%s\n' "$result" | grep -q '^result of test$'; then
        echo "lookup of $2 in $1 returned an unexpected result"
        exit 1
    fi
}

lookup first foo
lookup second zzzzz
lookup first foo

# Both the index and synonym tables must have separate user cache files.
cache_count=$(find "$XDG_CACHE_HOME/sdcv" -type f -name '*.oft' | wc -l | tr -d '[:space:]')
if [ "$cache_count" -ne 4 ]; then
    echo "expected four distinct user caches, found $cache_count"
    exit 1
fi
