#!/bin/bash
# msgdiff old.po new.po additions.po fixes.po [fixes_review.po]
# Compare old.po and new.po and generate fixes.po that contains only
# fixes and additions.po that contains only additions.
# If fixes_review.po is specified, then generate also human readable po
# differences review file.

RC=0
OLD_HEADER=false
WEB_BACKEND=false
if test "$1" = "--web-backend" ; then
	WEB_BACKEND=true
	shift
fi
if test "$1" = "--old-header" ; then
	OLD_HEADER=true
	shift
fi
PO_OLD=$1
PO_NEW=$2
PO_ADD=$3
PO_FIX=$4

PO_REV_PRESENT=false
if $WEB_BACKEND ; then
	if test -n "$5" ; then
		PO_REVFIX=$5
	else
		echo >&2 "WEB_BACKEND requires 5 arguments"
		exit 255
	fi
else
	if test -n "$5" ; then
		PO_REV=$5
		PO_REV_PRESENT=true
	fi
fi

TMP=$HOME/.msgdiff$$

trap "rm -rf $TMP" 0
mkdir -p $TMP

# Join both translations, string changes become fuzzy.
msgcat --force-po "$PO_OLD" "$PO_NEW" -o $TMP/allfz.po
# Join both translations, use new in case of change.
msgcat --use-first --force-po "$PO_NEW" "$PO_OLD" -o $TMP/all.po

# Compose the best po file header.
if $OLD_HEADER ; then
	${0%msgdiff}msgheadermerge "$PO_NEW" "$PO_OLD" $TMP/header.po --newdate
else
	${0%msgdiff}msgheadermerge "$PO_OLD" "$PO_NEW" $TMP/header.po --newdate
fi

# step 4: Find string fixes (existed before, now different).
msgcat --unique --force-po $TMP/all.po $TMP/allfz.po -o $TMP/fix.po
sed -i '/#~/d' $TMP/fix.po
msgcat --use-first $TMP/header.po $TMP/fix.po -o "$PO_FIX"
if $WEB_BACKEND ; then
	msgcat --use-first --force-po "$PO_OLD" "$PO_NEW" -o $TMP/allr.po
	msgcat --unique --force-po $TMP/allr.po $TMP/allfz.po -o $TMP/fixr.po
	sed -i '/#~/d' $TMP/fixr.po
	msgcat --use-first $TMP/header.po $TMP/fixr.po -o "$PO_REVFIX"
fi

# step 5: Find newly translated strings (translation removal is not supported).
msgcat --unique --force-po "$PO_OLD" $TMP/all.po -o $TMP/add.po
sed -i '/#~/d' $TMP/add.po
msgcat --use-first $TMP/header.po $TMP/add.po -o "$PO_ADD"

if $PO_REV_PRESENT ; then
	msgmerge --force-po $TMP/allfz.po $TMP/fix.po -o $TMP/review.po
	sed -i '/#~/d' $TMP/review.po
	msgcat $TMP/review.po -o "$PO_REV"
fi
