#!/bin/bash

# Note - this script requests bash because I use Bash and therefore it
# contains some Bashisms.  Your mileage may vary running it under another
# shell.

# Part of Password Gorilla

# Copyright 2011 - Richard L Ellis
# Copyright 2013 - Alexandre Raymond - script improvements

# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 675 Mass Ave, Cambridge, MA 02139, USA.
#
# A copy of the GNU General Public License may be found in the Password
# Gorilla sources/ directory, named LICENSE.txt.

# ./rebuild-msg-files [-f] [lang]

POPATH=gettext
HELPPATH=help2po

cd $(dirname $0)
if [[ -d ./msgs ]]; then
    echo
    echo "ERROR - this script must be run from the [gorilla-local-dir]/utilities directory"
    echo "It is being run from $PWD at present"
    echo "Unable to continue"
    echo
    exit 1
fi 

function mk-msg () {
    local OUTDIR=$1 ; shift
    for POFILE in "$@" ; do
        LANG=$( basename $POFILE .po )
        echo $POFILE LANG=$LANG
        msgfmt --tcl -l$LANG -d $OUTDIR $POFILE
    done
}


# Allow in-place refreshes
if [[ "$1" = "-f" ]]; then
    OUTDIR=../sources/msgs
    shift
else
    OUTDIR=$( mktemp -d )
fi

# Specific lang
TLANG="$1"
TLANG_POFILES="$(ls $POPATH/${TLANG}*.po 2>/dev/null)"
TLANG_HELPFILES="$(ls $HELPPATH/${TLANG}*.po 2>/dev/null)"

if [[ ! -z "$TLANG_POFILES" ]]; then
    # rebuild translation files
    mk-msg $OUTDIR $TLANG_POFILES
fi

if [[ ! -z "$TLANG_HELPFILES" ]]; then
    # rebuild help.txt files
    mkdir -p $OUTDIR/help

    mk-msg $OUTDIR/help $TLANG_HELPFILES
fi

if [[ ! -z "$TLANG_POFILES" ]] || [[ ! -z "$TLANG_HELPFILES" ]]; then
    # convert and add DO NOT EDIT header
    ./mcset2mcmset.tcl $(find $OUTDIR -type f -name "${TLANG}*.msg")

    # replace msg files with converted files
    for name in $( find $OUTDIR -name \*conv ) ; do
        mv -fv $name ${name/.conv}
    done
fi

echo
echo "New msg files have been created in $OUTDIR"
echo
