#!/bin/sh
# $Id: diff-patch,v 1.16 2022/04/16 23:55:31 tom Exp $
LANG=C;   export LANG
LC_ALL=C; export LC_ALL
TZ=UTC0;  export TZ
if test $# != 2
then	echo '? expected 2 arguments'
	exit 1
elif test ! -d $1 -o ! -d $2
then	echo '? both arguments must be directories'
	exit 1
else
	WD=`pwd`
	( cd $2 && find . -type f -print | sort |fgrep -v MD5sums| xargs md5sum >$WD/MD5sums )
	gap="# ------------------------------------------------------------------------------"
	tmp=$1.tmp
	out=$2.patch
	makepatch -diff "diff -u" $1 $2  >$tmp
	rm -f "$out"

	when_on=`date`
	whom_by=unknown
	if test -f "$HOME/.signature" ; then
		whom_by=`head -n 1 "$HOME/.signature"`
	else
		whom_by=`id | sed -e 's/^uid=[^(]*(//' -e 's/).*//'`
		if test -z "$whom_by" ; then
			if test -n "$LOGNAME" ; then
				whom_by="$LOGNAME"
			elif test -n "$USERNAME" ; then
				whom_by="$USERNAME"
			elif test -n "$USER" ; then
				whom_by="$USER"
			fi
		fi
		if test -f /etc/passwd ; then
			full=`egrep "^$whom_by:" /etc/passwd | sed -e 's/^[^:]*:[^:]*:[^:]*:[^:]*://' -e 's/:.*//' -e 's/[.,]*$//'`
			test -n "$full" && whom_by="$full" 
		fi
	fi

	# if it's one of my regular patches, add a line at the beginning
	# showing the expected url.
	URL=
	case $whom_by in #(vi
	*dickey*|*Dickey*)
		URL=https://invisible-island.net/archives
		case $2 in
		*[a-z][1-9]) #(vi
			URL=$URL/temp
			;;
		*)
			case `pwd` in #(vi
			*/ncurses) #(vi
				. ncurses-patches
				URL=$NCURSES_PATCHES
				;;
			*/vile) #(vi
				URL=$URL/vile/patches
				;;
			*/xterm) #(vi
				URL=$URL/xterm/patches
				case $2 in
				*[0-9][a-z]) #(vi
					URL=$URL/temp
					;;
				esac
				;;
			*)
				URL=
				;;
			esac
		esac
		;;
	esac

	test -n "$URL" && echo "# $URL/$out.gz" >>"$out"

	echo "# patch by $whom_by" >>"$out"
	echo "# created  $when_on" >>"$out"

	echo	$gap	>>"$out"
	diffstat -c -w78 $tmp >>"$out"
	echo	$gap	>>"$out"
	cat	$tmp	>>"$out"
	rm -f $1.tmp
fi
