#!/bin/sh
#
# This file is part of Rheolef.
#
# Copyright (C) 2000-2009 Pierre Saramito 
#
# Rheolef is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Rheolef is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Rheolef; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# -------------------------------------------------------------------------
#
# hack from zdiff in gzip package:
# fix the buggy exit status when arg == - is read from stdin
# 
# Pierre.Saramito@imag.fr
#
# date: 28 sept 2011
#
prog="zdiff"
comp="diff"
TMPDIR=${TMPDIR-"/tmp"}
OPTIONS=
FILES=
for ARG in $*; do
    case "$ARG" in
    -)	FILES="$FILES -";;
    -*)	OPTIONS="$OPTIONS $ARG";;
     *)	if test -f "$ARG"; then
            FILES="$FILES $ARG"
        else
            echo "${prog}: $ARG not found or not a regular file"
	    exit 1
        fi ;;
    esac
done
if test -z "$FILES"; then
	echo "Usage: $prog [${comp}_options] file [file]"
	exit 1
fi
set $FILES
tmp1="$TMPDIR/zdiff-1-$$"
tmp2="$TMPDIR/zdiff-2-$$"
if test $# -eq 1; then
	FILE=`echo "$1" | sed 's/[-.][zZtga]*$//'`
	gzip -d < "$1" > $tmp1
        $comp $OPTIONS $tmp1 "$FILE"
	STAT="$?"
	/bin/rm -f $tmp1
elif test $# -eq 2; then
	case "$1" in
        *[-.]gz* | *[-.][zZ] | *.t[ga]z)
                case "$2" in
	        *[-.]gz* | *[-.][zZ] | *.t[ga]z)
                        gzip -cdfq "$1" > $tmp1
                        gzip -cdfq "$2" > $tmp2
                        $comp $OPTIONS $tmp1 $tmp2
                        STAT="$?"
			/bin/rm -f $tmp1 $tmp2
			;;
                *) 
                        gzip -cdfq "$1" > $tmp1
			$comp $OPTIONS $tmp1 "$2"
                        STAT="$?"
			/bin/rm -f $tmp1
			;;
                esac;;
        *)      case "$2" in
	        *[-.]gz* | *[-.][zZ] | *.t[ga]z)
                        gzip -cdfq "$2" > $tmp2
			$comp $OPTIONS "$1" $tmp2
                        STAT="$?"
			/bin/rm -f $tmp2
			;;
                *)      $comp $OPTIONS "$1" "$2"
                        STAT="$?"
			;;
                esac;;
	esac
        exit "$STAT"
else
	echo "Usage: $prog [${comp}_options] file [file]"
	exit 1
fi
