#!/bin/sh -
umask 077

diff=${DIFF-diff}
wdiff=${WDIFF-dwdiff}
vidiff=${VIDIFF-vimdiff}
tdiff=${TDIFF-tdiff}
view="view -c \"sy clear|so \\\$VIMRUNTIME/syntax/\$DIFF.vim\""

# diffcb - diff the first two X11 cut buffers (else primary else clipboard)
# Steve Kinzler, steve@kinzler.com, Aug 08/Nov 08/Nov 10
# https://kinzler.com/me/home.html#x11

case "$1" in
-h|--help)	echo "usage: $0 [ d | D | w | W | v | h | H ] [ diff options ]
	d	output a regular diff ($diff)
	D	view a regular diff ($diff)
	w	output a word diff ($wdiff)
	W	view a word diff ($wdiff)
	v	edit a diff ($vidiff)
	h	output a word diff in HTML ($tdiff)
	H	view a word diff in HTML ($tdiff)
The diffed texts are the first two X11 cut buffers, although if either
is empty, then the primary selection buffer is used instead.
The viewer is '$view'" 1>&2; exit 1;;
[hH])		type="$1"; shift; DIFF=tdiff;  differ="$tdiff";;
[vV])		type="$1"; shift; DIFF=vidiff; differ="$vidiff";;
[wW])		type="$1"; shift; DIFF=wdiff;  differ="$wdiff";;
[dD])		type="$1"; shift; DIFF=diff;   differ="$diff";;
*)		type=d;		  DIFF=diff;   differ="$diff";;
esac

tmp0=/tmp/diffcb$$A
tmp1=/tmp/diffcb$$B
trap "rm -fr $tmp0 $tmp1; exit" 0 1 2 13 15

#buf -O b 0 p > $tmp0
xbuf -O 0 p b > $tmp0
xbuf -O 1 p b > $tmp1

case "$DIFF" in
tdiff)	case "$type" in
	[a-z])	set x -o "$@"; shift;;
	esac
	exec $differ "$@" $tmp0 $tmp1;;

vidiff)	$differ "$@" $tmp0 $tmp1
	(rmview $tmp0 $tmp1) > /dev/null 2>&1;;

*)	$differ "$@" $tmp0 $tmp1 |
	case "$type" in
	[A-Z])	eval $view;;
	*)	cat;;
	esac;;
esac
