#!/usr/bin/env bash
#
# dif - interactive diff with pagination and nice coloring
# dependencies: diffr (diff-color)

# shellcheck shell=bash
set -e

declare -a files
while test "$#" -gt 0; do
  test "$1" == "--" \
    && shift \
    && command="$@" \
    && break
  files+=("$1")
  shift
done
{
  # shellcheck disable=SC2312
  if ! test "${command}"; then
    mime="$(file --brief --mime "${files[@]}")"
    case "${mime}" in
      *audio*)
        command="ffprobe -loglevel warning -print_format default=noprint_wrappers=1 -show_format -pretty"
        ;;
      image/*)
        command="exiftool"
        ;;
      *sqlite*)
        # TODO: syntax highlighting for INSERT/UPDATE/DELETE
        sqldiff --summary "${files[@]}" | grep -v '0 changes, 0 inserts, 0 deletes'
        ;;
      text/*)
        diff --color=always -U 1 -s "${files[@]}"
        ;;
      *)
        # -s --report-identical-files
        diff-color -s "${files[@]}"
        ;;
    esac
  fi

  # shellcheck disable=SC2312
  if test "${command}"; then
    echo "Generated through ${command}"
    $(test "$(tput cols)" -gt 120 && echo "diff --color=always --side-by-side" || echo "diff-color") \
      --ignore-case --report-identical-files --label="${files[0]}" --label="${files[1]}" <(${command} "${files[0]}") <(${command} "${files[1]}")
  fi
} | less --RAW-CONTROL-CHARS --quit-on-intr --quit-if-one-screen
