#!/bin/bash

set -e

# To guarantee that files may be written by the group
umask 002

GENCOMPENDIUMPATH=${GENCOMPENDIUMPATH='.'}

. "$GENCOMPENDIUMPATH"/l10n.conf

#create a local tmp directory
POTMPDIR=`mktemp -d "$TMPDIR"/cpd.XXXXXXXXXX`
# cleanup local tmp directory on exit
trap 'rm -rf "$POTMPDIR"' 0

[ $# = 1 ] && MSGLANG=$1 || exit 1

find "$SITEDIR" -name "*_${MSGLANG}.po.gz" -exec cp {} "$POTMPDIR" \;
gunzip "$POTMPDIR"/*
RESULTS="$RESULTS/$MSGLANG"
mkdir -p "$RESULTS"

exec &>"$RESULTS/$STAMP.log"
# for some odd reason convert_or_remove needs to be an external file
# maybe because find doesn't have it defined in its environment
find "$POTMPDIR" -name *.po -exec ./convert_or_remove {} \;
msgcat -o "$RESULTS/compendium-$MSGLANG-stamp$STAMP.po" $POTMPDIR/*.po || {
	echo "EEE: failed to generate $RESULTS/compendium-$MSGLANG-stamp$STAMP.po"
	exit 1
}


echo "III: generated $RESULTS/compendium-$MSGLANG-stamp$STAMP.po"

# In order to be useful, the latest compendium needs to be used by users
ln -sf "$RESULTS/compendium-$MSGLANG-stamp$STAMP.po" "$RESULTS/compendium-$MSGLANG-LATEST.po"
# Remove old compendia and log files if we were successful
find "$RESULTS" -name "2*.log" -a -mtime "+1" -delete
find "$RESULTS" -name "compendium-*.po" -a -mtime "+1" -delete
