#!/bin/sh

[ -n "$ZSH_VERSION" ] || exec zsh -f -- "$0" ${1+"$@"}

# External/extended diff for svn, in particular.
# Copyright 2014-2024 Vincent Lefevre <vincent@vinc17.net>.

# This program 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 3 of the License, or
# (at your option) any later version.

# This program 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 this program; if not, see <https://www.gnu.org/licenses/>.

# Note: this script could normally start with "#!/usr/bin/env zsh" and
# avoid the "exec zsh" line. But with "svn diff --diff-cmd" in Termux
# under Android 14, this gives the following error:
#   exec of 'ext-diff' failed: No such file or directory
# See
#   https://github.com/termux/termux-packages/issues/18537
#   https://lists.apache.org/thread/6cvt24hkn7bcptgojsotoqcsonrz03y6

# It is unfortunately not possible to diff encrypted files (in the cases
# where the passphrase is cached), because the information about whether
# a file is encrypted is not available for the diff command (i.e., this
# script).

process()
{
  if [[ $(head -c 13 $1) == '{"entities":{' ]] then
    json_pp --json_opt canonical,pretty,utf8 < $1
    return
  fi
  case $(file $1) in
    *"Java serialization data"*)
      jdeserialize $1 ;;
    *"OpenDocument"*)
      sxw2txt $1 ;;
    *"PDF document"*)
      pdftotext $1 - ;;
    *"SQLite 3.x"*)
      sqlite3 $1 .dump ;;
    *"vCalendar calendar file"*|*"vCard visiting card"*)
      sed 's/\r$//' $1 ;;
    *"XZ compressed data"*)
      unxz -c $1 ;;
    *"Zip archive data"*)
      list=$(unzip -v $1 | grep -v '^Archive:')
      if [[ $list == *\ geogebra.xml$'\n'* ]] then
        unzip -cq $1 geogebra.xml
      else
        printf "%s\n" $list
      fi
      ;;
    *)
      # The "2>/dev/null" avoids a "cat: write error: Broken pipe"
      # error message when diff detects binary files.
      cat $1 2>/dev/null ;;
  esac
}

diff "$@[0,-3]" <(process "$@[-2]") <(process "$@[-1]")

# Workaround to diffutils bug 16608 (Debian bug 737180).
err=$?
if [[ -n $BROKEN_DIFF && $err -eq 2 ]] then
  out=$(diff "$@" 2>/dev/null)
  if [[ $out == "Binary files "*" differ" ]] then
    echo "[Fixed wrong exit status due to diffutils bug 16608]"
    err=1
  fi
fi
exit $err

# $Id: ext-diff 171414 2024-09-01 12:33:49Z vinc17/qaa $