#!/bin/bash

#
# Set up tmp file
#

POTMP=${TMPDIR:-${TMP:-/tmp}}
if [ ! -d $POTMP -o ! -w $POTMP ]
then
	echo $POTMP does not exist or is not writable
	exit 1
fi
TMPFILE=`mktemp $POTMP/poedit.XXXXXX` || exit 1

#
# Check what msgs to include
#

if [ "$1" = "-a" ]
then
	INCLUDE_ALL_MSGS=yes
	POFILE="$2"
else
	INCLUDE_ALL_MSGS=no
	POFILE="$1"
fi

#
# Some sanity checks
#

if [ -z "$POFILE" -o ! -w "$POFILE" ]; then
	echo 'edit what?!' 1>&2
	exit 1
fi

if [ -z "$EDITOR" ]; then
	echo '$EDITOR is not set1' 1>&2
	exit 1
fi

#
# Filter the file
#

if [ "$INCLUDE_ALL_MSGS" = "yes" ]
then
	potool "$POFILE" -ft > "$TMPFILE"
	echo >> "$TMPFILE"
else
	echo -n '' > "$TMPFILE"
fi
potool "$POFILE" -fnt >> "$TMPFILE"

#
# Run editor and update the file on success
#

$EDITOR "$TMPFILE"
if [ $? -eq 0 ]; then
	mv "$POFILE" "$POFILE~"
	potool "$POFILE~" "$TMPFILE" > "$POFILE" 
	if [ $? -eq 0 ]; then
		printf "Before: %s/%s\n" `potool -ft -s "$POFILE~"` `potool -s "$POFILE~"` 
		printf "After:  %s/%s\n" `potool -ft -s "$POFILE"` `potool -s "$POFILE"` 
		rm -f "$POFILE~" "$TMPFILE"
	else
		mv -f "$POFILE~" "$POFILE"
		echo "Temp. file: " $TMPFILE
	fi
else
	echo $EDITOR exited abnormally, not updating the po file
	exit 1
fi
