#!/usr/bin/env bash
#
# --- T2-COPYRIGHT-NOTE-BEGIN ---
# T2 SDE: scripts/Create-Diff
# Copyright (C) 2004 - 2023 The T2 SDE Project
# Copyright (C) 1998 - 2003 ROCK Linux Project
# 
# This Copyright note is generated by scripts/Create-CopyPatch,
# more information can be found in the files COPYING and README.
# 
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2.
# --- T2-COPYRIGHT-NOTE-END ---

directories="misc package architecture target scripts"

if [ "$1" = "-editor" ]; then
	editor="$2"; shift; shift
fi

if [ "$#" -lt 2 ]; then
	echo; echo "  Usage: $0 [ -editor <editor> ] <old-dir> <new-dir> [ {file|directory} ]"
	echo
	echo "  Creates a unified diff over two T2 source trees. You can"
	echo "  send this diff to the mailing list if you want your changes"
	echo "  to be included."
	echo
	echo "  Please do create seperate diffs for changes which do not"
	echo "  belong to each other."
	echo; exit 1
else
	olddir=$1; shift
	newdir=$1; shift
	[ "$1" ] && directories="$*"
fi

if ! perl -e 'exit 0'; then
	perl() { cat; }
fi

eval "`grep -A 10 '\[BEGIN\]' $olddir/scripts/parse-config | grep -B 10 '\[END\]'`"

[ "$editor" = "" ] && echo "[ Generated by scripts/Create-Diff for T2 $sdever ]" > /tmp/$$

for x in $directories; do
	x=${x#./} x=${x%/}
	if [ -d $x ]; then
		FLAGS="-rduN"
		name_for_diff="$x/."
		source_for_sed="$x/./"
		target_for_sed="$x/"
	else
		FLAGS="-duN"
		name_for_diff="$x"
		source_for_sed=""
		target_for_sed=""
	fi
	diff -x CVS -x '.svn' -x '.#*' -x '*.mine' -x '*.r[1-9][0-9]*' \
		$FLAGS "$olddir"/$name_for_diff "$newdir"/$name_for_diff | grep -v '^diff ' | \
	sed "s,^--- $olddir/$source_for_sed,--- ./$target_for_sed," | \
	sed "s,^+++ $newdir/$source_for_sed,+++ ./$target_for_sed," | \
	perl -pe '$fn=$1 if /^--- \.\/(\S+)\s/;
		$_="" if $fn =~ /~$/'
done >> /tmp/$$

if [ "$editor" = "" ]; then
	cat /tmp/$$
	rm /tmp/$$
else
	eval "$editor /tmp/$$"
	rm /tmp/$$
fi