#!/usr/bin/bash
export PATH=@MINGW_PREFIX@/bin:$PATH
FMTUTIL="@MINGW_HOOK_TARGET_PREFIX@/etc/texmf/web2c/fmtutil.cnf"
FMTUTILLOCAL="@MINGW_HOOK_TARGET_PREFIX@/etc/texmf/web2c/fmtutil-local.cnf"

LANGUAGE_DEF="@MINGW_HOOK_TARGET_PREFIX@/etc/texmf/tex/generic/config/language.def"
LANGUAGE_DAT="@MINGW_HOOK_TARGET_PREFIX@/etc/texmf/tex/generic/config/language.dat"
LANGUAGE_DAT_LUA="@MINGW_HOOK_TARGET_PREFIX@/etc/texmf/tex/generic/config/language.dat.lua"

cp @MINGW_HOOK_TARGET_PREFIX@/share/texmf-dist/web2c/fmtutil-hdr.cnf $FMTUTIL
for file in @MINGW_HOOK_TARGET_PREFIX@/var/lib/texmf/msys2/installedpkgs/*.fmts; do
    echo >> $FMTUTIL
    echo "# $file" >> $FMTUTIL
    cat $file >> $FMTUTIL
done
if [[ -f "$FMTUTILLOCAL" ]]; then
    echo >> $FMTUTIL
    echo "# $FMTUTILLOCAL" >> $FMTUTIL
    cat "$FMTUTILLOCAL" >> $FMTUTIL
fi

cp @MINGW_HOOK_TARGET_PREFIX@/etc/texmf/tex/generic/config/language.us.def $LANGUAGE_DEF
for file in @MINGW_HOOK_TARGET_PREFIX@/var/lib/texmf/msys2/installedpkgs/*.def; do
    echo >> $LANGUAGE_DEF
    echo "% $file" >> $LANGUAGE_DEF
    cat $file >> $LANGUAGE_DEF
done
echo -e "%%% No changes may be made beyond this point.\n" >> $LANGUAGE_DEF
echo "\uselanguage {USenglish}             %%% This MUST be the last line of the file." >> $LANGUAGE_DEF
echo >> $LANGUAGE_DEF # new line

cp @MINGW_HOOK_TARGET_PREFIX@/etc/texmf/tex/generic/config/language.us $LANGUAGE_DAT
for file in @MINGW_HOOK_TARGET_PREFIX@/var/lib/texmf/msys2/installedpkgs/*.dat; do
    echo >> $LANGUAGE_DAT
    echo "% $file" >> $LANGUAGE_DAT
    cat $file >> $LANGUAGE_DAT
done
echo >> $LANGUAGE_DAT # new line

cp @MINGW_HOOK_TARGET_PREFIX@/etc/texmf/tex/generic/config/language.us.lua $LANGUAGE_DAT_LUA
for file in @MINGW_HOOK_TARGET_PREFIX@/var/lib/texmf/msys2/installedpkgs/*.dat.lua; do
    echo >> $LANGUAGE_DAT_LUA
    echo "-- $file" >> $LANGUAGE_DAT_LUA
    cat $file >> $LANGUAGE_DAT_LUA
done
echo '}' >> $LANGUAGE_DAT_LUA
echo >> $LANGUAGE_DAT_LUA # new line

# remove mflua-nowin it fails
sed -i 's/mflua mflua-nowin - mf.ini//' $FMTUTIL

echo ">>> Running fmtutil (this might take a while)"
# Run mktexlsr since /etc/texmf/tex/generic/config/language.* can be a new files
@MINGW_PREFIX@/bin/mktexlsr
@MINGW_PREFIX@/bin/fmtutil-sys --all --cnffile $FMTUTIL > /dev/null
