#!/bin/bash
# --- T2-COPYRIGHT-NOTE-BEGIN ---
# This copyright note is auto-generated by ./scripts/Create-CopyPatch.
# 
# T2 SDE: scripts/Commit
# Copyright (C) 2004 - 2009 The T2 SDE Project
# 
# 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 as published by
# the Free Software Foundation; version 2 of the License. A copy of the
# GNU General Public License can be found in the file COPYING.
# --- T2-COPYRIGHT-NOTE-END ---

if [ -z "$1" ] ; then
	echo "Usage $0 package/files"
	exit
fi

trap 'echo "Got SIGINT (Crtl-C)." ; rm $$.log $$.diff ; exit 1' INT

locations=
for x; do
	[ ! -e "$x" -a -e `echo package/*/$x` ] &&
		x=`echo package/*/$x`
	locations="$locations $x"
done



# CopyPatch and Checksum and CkSumPatch
#
svn st $locations | grep '^\(A\|M\)' | cut -c8- | while read f; do
	if [ -f $f ]; then
		./scripts/Create-CopyPatch $f | patch -p0
		if [[ $f = *.desc ]] && grep '\[D\] \+0 \+' $f; then
			pkg=${f%.desc} pkg=${pkg##*/}
			./scripts/Create-CkSumPatch $pkg | patch -p0
		fi
	fi
done

visualize_warnings() {
	# do not highlight just single space diff lines
	sed '/^[+ -]./ s/\([[ \r\t]]*\)$/\o033[0;41m\1\o033[0m/'
}

echo "Diff:"
svn diff $locations | tee $$.diff | visualize_warnings

# the grep -v === is a hack - somehow the svn === lines confuse awk ... ?!?
grep -v === $$.diff | awk "
	BEGIN { FS=\"[ /]\" }

	/^\+\+\+ / { pkg = \$4 }
	{ if (sub(/^\+\[I\]/,\" -\") ) { info = \$0 } }

	/^\-\[V\] / { oldver=\$2 }
	/^\+\[V\] / {
		newver=\$2
		if ( oldver )
		  print \"\t* updated \" pkg \" (\" oldver \" -> \" newver \")\"
		else {
		  print \"\t* added \" pkg \" (\" newver \")\" info
		}
		oldver=\"\" ; newver=\"\" ; info=\"\"
	}

	/^\-\[P\] / { oldprio=\$4 }
	/^\+\[P\] / {
		newprio=\$4
		if ( oldprio )
		  print \"\t* changed \" pkg \" build priority (\" oldprio \" -> \" newprio \")\"
		oldprio=\"\" ; newprior=\"\"
	}

" > $$.log

if [ -s $$.diff ]; then
	quit=0
	until [ $quit -ne 0 ]; do

		echo -e "\nLog:"
		if [ -s $$.log ]; then
			cat $$.log
			commit=",c=commit"
		else
			echo -e "\tEmpty Log File!"
			commit=
		fi
		
		echo -en "\nLog ok (q=quit,e=edit,d=diff,s=status$commit)? "
		read in

		case "$in" in
		  c*)	if [ -n "$commit" ]; then
		  		svn commit $locations --file $$.log ; quit=1
			fi ;;
		  d*)	cat $$.diff | visualize_warnings | less -R ;;
		  s*)	svn st $locations ;;
		  e*)	${EDITOR:-vi} $$.log ;;
		  q*)	quit=1 ;;
		  *)	echo "Excuse me?"
		esac
	done
else
	echo -e "\nNo changes detected at:$locations"
	svn st $locations
fi

rm $$.log $$.diff

