#! /bin/sh

# Script acceptable as a value for GIT_EXTERNAL_DIFF.
# For example, you can see the changes in your working tree with
# 
# $ GIT_EXTERNAL_DIFF=git-oodiff diff

clean_up ()
{
    rm -f /tmp/oodiff.$$.{1,2}
}

convert_to_txt ()
{
    if [ x"$1" = x"/dev/null" ]; then
        : > /tmp/oodiff.$$."$2"
        eval "label$2=/dev/null/"
    else
        odt2txt "$1" > /tmp/oodiff.$$."$2" 2>/dev/null
    fi
}

Main ()
{
    if [ ! "$1" ]; then
	echo "$0: [ERROR] Input argument missing" >&2
	return 1
    fi

    label1="a/$1"
    label2="b/$1"

    if [ "$#" = "1" ]; then
	echo "Unmerged path $1"
	exit 0
    fi

    msg=""

    if [ x"$4" = x"." ]; then
	msg="new file mode $7\n"
    elif [ x"$7" = x"." ]; then
	msg="deleted file mode $4\n"
    elif [ x"$4" != x"$7" ]; then
	msg="old mode $4\nnew mode $7\n"
    fi

    if convert_to_txt "$2" "1" &&
       convert_to_txt "$5" "2"
    then
	echo $(basename $0) "$label1" "$label2"
	echo -e "$msg"

	if diff -L "$label1" -L "$label2" -u /tmp/oodiff.$$.{1,2}; then
	    # no text change
	    if diff -q "$2" "$5"; then
		: # no change at all
	    else
		echo "OpenDocument files a/$1 and b/$1 files differ (same text content)"
	    fi
	fi
    else
	# conversion failed. Fall back to plain diff.
	echo diff -u "$label1" "$label2"
	echo -e "$msg"
	diff -L "$label1" -L "$label2" -u "$2" "$5"
    fi
}

Main "$@"
trap 'clean_up; exit 0' 1 2 3 15
