#!/usr/bin/env bash

# This script contains command for quick POS dictionary and SYNTH_ dictionary generation.
# Shell scripts (or rather, symbolic links to "ltshell") are generated by LT RPM module.

rm_temp_files() {
    # It was observed that process leaves temporary files in /tmp directory
    # so we will clean up after ourselves
    echo -n "Cleaning up ... "
    rm -f ${TEMPDIR}/DictionaryBuilder*txt ${TEMPDIR}/DictionaryBuilder*info \
      ${TEMPDIR}/SynthDictionaryBuilder*txt ${TEMPDIR}/SynthDictionaryBuilder*info \
      ${TEMPDIR}/SpellDictionaryBuilder*txt ${TEMPDIR}/SpellDictionaryBuilder*info
    echo "done."
}

trap 'rm_temp_files' EXIT SIGINT SIGTERM

DIALECT=$1

if [ "$DIALECT" == "e" ]; then
    DIADESC=ekavian
elif [ "$DIALECT" == "i" ]; then
    DIADESC=jekavian
else
    echo "Unknown Serbian dialect '${DIALECT}', aborting ..."
    exit 1
fi

# Adjust as needed
MYDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
INPUT_DIR=/opt/app/s/smd/lt
CORPUS_FILE=${INPUT_DIR}/synth-serbian-${DIADESC}-corpus.txt
CORPUS_HUNSPELL_FILE=${INPUT_DIR}/hunspell-serbian-${DIADESC}-corpus.txt
DICT_DIR=dictionary
DICTIONARY_PATH=${DICT_DIR}/${DIADESC}
TEMPDIR=/tmp
FREQFILE=${INPUT_DIR}/serbian-${DIADESC}-wordlist.xml

if [ ! -f ${CORPUS_FILE} ]; then
    echo "Serbian word corpus file ${CORPUS_FILE} does not exist, aborting ..."
    exit 1
fi

echo "Generating Serbian ${DIADESC} POS dictionary ..."
ltposdic -i ${CORPUS_FILE} -info ${MYDIR}/../${DICT_DIR}/serbian.info \
    -freq ${FREQFILE} -o ${MYDIR}/../${DICTIONARY_PATH}/serbian.dict

echo "Generating Serbian SYNTH ${DIADESC} dictionary ..."
ltsyndic -i ${CORPUS_FILE} -info ${MYDIR}/../${DICT_DIR}/serbian_synth.info \
    -o ${MYDIR}/../${DICTIONARY_PATH}/serbian_synth.dict

echo "Generating Serbian HunSpell ${DIADESC} dictionary ..."
ltspldic -i ${CORPUS_HUNSPELL_FILE} -info ${MYDIR}/../${DICT_DIR}/serbian.info \
    -freq ${FREQFILE} -o ${MYDIR}/../${DICTIONARY_PATH}/serbian_hunspell.dict
