#!/bin/sh
#
# idiff - color diff output, for human consumption
#
# note:
#    If 2 parameters are passed, then they are passed to
#    the `diff -Naru` command first. Otherwise the parameters
#    (or stdin) are assumed to be diff format and are colourised.
#
#    VIM can be useful for viewing diffs also:
#      diff -Naru a b | vim -R -
#      vim -R a-b.diff
#
# ---
# source: https://www.pixelbeat.org

# less -K reportedly not available on older Mac OS X
less -K -Ff /dev/null 2>/dev/null && CTRL_C_EXITS="-K"

RED=1
GREEN=2
BLUE=4
BRIGHT='1;'

tputc() {
  bright=$1
  colour=$2
  [ -n "${bright}" ] && tput bold
  tput setaf "${colour}"
}

DEL="$(tputc "${BRIGHT}" "${RED}")"
ADD="$(tputc "${BRIGHT}" "${GREEN}")"
CHG="$(tputc "${BRIGHT}" "${BLUE}")"
# highlight file level items
FIL="$(tput smso)"
RST="$(tput sgr0)"

# shellcheck disable=SC2250
if [ "$#" -eq "2" ]; then
  diff -Naru "$@"
else
  cat "$@"
fi \
  | sed "
s/^\*\{3\}.*\*\{4\}/$CHG&$RST/;t
  s/^-\{3\}.*-\{4\}/$CHG&$RST/;t
             s/^@.*/$CHG&$RST/;t
         s/^[0-9].*/$CHG&$RST/;t
             s/^!.*/$CHG&$RST/;t

             s/^-.*/$DEL&$RST/;t
             s/^<.*/$DEL&$RST/;t

            s/^\*.*/$ADD&$RST/;t
            s/^\+.*/$ADD&$RST/;t
             s/^>.*/$ADD&$RST/;t

       s/^Only in.*/$FIL&$RST/;t
       s/^Index: .*/$FIL&$RST/;t
         s/^diff .*/$FIL&$RST/;t
" \
  | ${PAGER:-less -QRS $CTRL_C_EXITS}

# could use less -EFX also, but for large files or lots of scrolling,
# this is a lot more obtrusive on the terminal as the [de]init codes not used.
