#!/bin/sh

tmpd="${TMPDIR:-/tmp}/test$$"
trap "rm -r '$tmpd'" HUP INT ALRM TERM 0

# Helper for the test runner: pass environment variable
# TEST_RUNNER_REFERENCE_DIR to save the PO and MO files.
if [ -d "$TEST_RUNNER_REFERENCE_DIR" ]; then
  outd="$TEST_RUNNER_REFERENCE_DIR"
else
  outd="$tmpd"
fi
set -e

mod="$outd/${LANG%%_*}/LC_MESSAGES"
mkdir -p "$mod" "$tmpd"

mdf=$(readlink -f "$0")
mdf=${mdf%.sh}
myf=${mdf##*/}

[ -e "$mdf.md" -a -n "$MDVIEW" ]

### Extract POT file, and translate it to PO file
$MDVIEW --po "$mdf.md" > "$tmpd/$myf.a.po"
if [ -s "$tmpd/$myf.a.po" ]; then
  msguniq -i "$tmpd/$myf.a.po"
fi |
  tee "$tmpd/$myf.pot" |
  # translation replaces letters with uppercase equivalents
  awk '###awk {{{
/^msgid/,/^msgstr/ {
if ($1 == "msgid") {
  delete R; nR=0
  insertR($0); print
}
else if ($1 != "msgstr") {
  insertR($0); print
}
else {
  sub(/msgid/, "msgstr", R[1])
  print "msgstr\t" toupper(R[1])
  for (i = 2; i <= nR; i++)
    print "\t" toupper(R[i])
}
next
}
{ print }
function insertR(s) {
R[++nR] = substr(s, index(s, "\""))
}
  ###awk }}}
    ' > "$outd/$myf.po"

### Convert PO file to MO file
msgfmt -o "$mod/$myf.mo" "$outd/$myf.po"

### Run mdview to view the translation
env TEXTDOMAINDIR="$outd" $MDVIEW "$mdf.md"
