#!/bin/sh

usage()
{
    if [ -n "$1" ]; then
	echo -e $*
    fi
    echo
    echo "Usage: "
    echo "   update-po \$domain \$src_dir \$src_file \$src_file ..."
    echo
    echo "For example, to generate po/\$lang/blades-client.po files for all "
    echo "existing language directories, you would call it like this:"
    echo
    echo "   update_po blades-client \\"
    echo "       \$PWD/root/usr/share/perl5/vendor_perl/esmith/Blades \\"
    echo "       Blade.pm Connection.pm Error.pm Package.pm Session.pm"
    echo
    echo "This assumes that all source files are in that same directory, "
    echo "and that no other options are needed.  This script is a first pass"
    echo "so we may need to augment it as we go."
    
    exit 1
}

DOMAIN=$1
SRC_DIR=$2
shift 2
SRC_FILES=$*

# Sanity checks

if [ -z "$DOMAIN" ]; then 
    usage "ERROR: Missing \$domain parameter"
fi
if [ ! -d "$SRC_DIR" ]; then 
    usage "ERROR: Invalid or missing \$src_dir parameter"
fi
if [ -z "$SRC_FILES" ]; then 
    usage "ERROR: You must specify at least one \$src_file parameter"
fi
for file in $SRC_FILES; do
    if [ ! -f "$SRC_DIR/$file" ]; then
	usage "ERROR: \$src_file not found: $file"
    fi
done

# Do it

PO_REF="${DOMAIN}.po"
# Send stderr to /dev/null because xgettext complains about irrelevant
# things due to the fact that it thinks it is reading C++ code. 
xgettext -C -d ${DOMAIN} -k'gettext' -D $SRC_DIR $SRC_FILES 2>/dev/null
if [ $? -ne 0 ]; then
    usage "Uh-oh, xgettext failed!\n" \
	  "Try running it manually and checking the errors:\n" \
	  "\txgettext -C -d ${DOMAIN} -k'gettext' -D $SRC_DIR $SRC_FILES"
fi

for lang in $(ls --color=never po -I CVS); do
    echo -n "updating .po file for $DOMAIN ($lang)"
    PO="$PWD/po/$lang/${DOMAIN}.po"
    msgmerge $PO $PO_REF -o $PO
done
rm $PO_REF
