#! /bin/bash

# FIXME:
TMPDIR=$PWD
TEMP=$TMPDIR/msgdiff.po-cut$1

#set -x

function format_string ()
{
	echo "$2" |
		if $1 ; then
			sed 's%&%\&amp;%g;s%<%\&lt;%g;s%>%\&gt;%g;s%$%<br />%g'
		else
			sed 's%&%\&amp;%g;s%<%\&lt;%g;s%>%\&gt;%g;s%$%\&#10;%g'
		fi |
		if test "${2%
}" = "$2" ; then if $1 ; then sed '$s%<br />$%%' ; else sed '$s%&#10;$%%' ; fi ; else cat ; fi | tr -d '\n'
}

STARTING_STRING=true
STARTING_PLURAL=false
RUNNING_PLURAL=false
if test -f $TMPDIR/msgdiff.plural-in-progress$1 ; then
	if test "${MSGEXEC_MSGID_PLURAL+yes}" = "yes" -a "$MSGEXEC_PLURAL_FORM" != 0 ; then
		RUNNING_PLURAL=true
		STARTING_STRING=false
	else
		rm $TMPDIR/msgdiff.plural-in-progress$1
		echo '</div>'
	fi
fi
if test "${MSGEXEC_MSGID_PLURAL+yes}" = "yes" -a "$MSGEXEC_PLURAL_FORM" = 0 ; then
	STARTING_PLURAL=true
	RUNNING_PLURAL=true
	touch $TMPDIR/msgdiff.plural-in-progress$1
fi

if $STARTING_STRING ; then
	echo '<div class="po-item">'

	if $2 ; then
		echo -n '<h2 class="po-string">Changed string</h2>'
	else
		echo -n '<h2 class="po-string">Added string</h2>'
	fi

	# Do if msgctxt is present (it may be empty):
	if test "${MSGEXEC_MSGCTXT+yes}" = "yes" ; then
		echo '<p>Context:</p>'
		echo -n '<pre class="po-msgctxt">'
		format_string true "$MSGEXEC_MSGCTXT"
		echo -n '</pre>'
	fi

	echo '<p>English string:</p>'
	echo -n '<pre class="po-msgid">'
	format_string true "$MSGEXEC_MSGID"
	echo -n '</pre>'

	if $STARTING_PLURAL ; then
		echo '<p>Plural form of English string:</p>'
		echo -n '<pre class="po-msgid">'
		format_string true "$MSGEXEC_MSGID_PLURAL"
		echo -n '</pre>'
	fi
fi


if test -n "$MSGEXEC_PLURAL_FORM" ; then 
	echo '<form class="plural-form">'
	echo '<h3 class="po-string">Plural form '"$MSGEXEC_PLURAL_FORM"'</h3>'
else
	echo '<form>'
fi

if $2 ; then
	CNT=$(<$TEMP/CNT)

	# Trick: bash ignores trailing EOL. Work-around it by adding "END"
	MSGEXEC_MSGSTR_ORIG="$(cat $TEMP/$CNT ; echo END)"
	MSGEXEC_MSGSTR_ORIG="${MSGEXEC_MSGSTR_ORIG%END}"
	echo '<p>Original translation:</p>'
	echo -n '<input type="radio" name="FIXME" value="orig" />'
	echo -n '<pre class="po-msgstr-orig">'
	format_string true "$MSGEXEC_MSGSTR_ORIG"
	echo '</pre>'

	let CNT++
	echo $CNT >$TEMP/CNT
fi

# Trick: bash ignores trailing EOL. Work-around it by adding "END"
MSGEXEC_MSGSTR="$(cat ; echo END)"
MSGEXEC_MSGSTR="${MSGEXEC_MSGSTR%END}"
	echo '<p>Proposed translation:</p>'
	echo -n '<input type="radio" name="FIXME" checked="checked" value="new" />'
echo -n '<pre class="po-msgstr">'
format_string true "$MSGEXEC_MSGSTR"
echo '</pre>'

	echo '<p>Or specify custom translation:</p>'
	echo '<input type="radio" name="FIXME" value="custom" />'
	echo '<form class="po-msgstr-custom">'
	echo -n '<div class="po-msgstr-custom"><textarea class="po-msgstr-custom" name="FIXME" rows="'$(echo "$MSGEXEC_MSGSTR" | wc -l)'">'
	format_string false "$MSGEXEC_MSGSTR"
	echo '</textarea></div>'
	echo '</form>'

echo '</form>'

if ! $RUNNING_PLURAL ; then
	echo '</div>'
fi
