#!/bin/bash

# Parameters - PATHS can be set as $1.
BUILD_PARAMS='ARCH=um'
#Paths where to act
PATHS="arch/um include/asm-um"
[ -n "$1" ] && PATHS="$1"
COMPILE_TEST=0
PATCH_NAME=style-fixes-auto
[ -d "$OUT" -a -z "$KBUILD_OUTPUT" ] && KBUILD_OUTPUT=$OUT

# Customize for your source manager. {{{
new_patch() {
	#Broken when the patch already exists.
	if ! quilt new $PATCH_NAME; then
		# A patch can be applied but still not exist, if it's empty or
		# it hasn't been refreshed.
		#if [ -f patches/$PATCH_NAME ]; then

		if ! grep $PATCH_NAME .pc/applied-patches; then
			quilt push $PATCH_NAME
		else
			quilt pop $PATCH_NAME || echo "quilt pop failed!" && exit 1
		fi
	fi
}

add_to_patch() {
	#Always works.
	quilt add "$1"
}

patch_refresh() {
	quilt refresh --strip-trailing-whitespace
}
# }}}

#Functions for compile diffing {{{
compile_file() {
	export KBUILD_OUTPUT
	name=$1
	if [ "${name#.c}" != "$name" ]; then
		obj=${name#.c}.o
		make $BUILD_PARAMS $obj
		unset prefix
		[ -n "$KBUILD_OUTPUT" ] && prefix=$KBUILD_OUTPUT/
		echo ${prefix}${obj}
	fi
}

save_compiled() {
	out=`compile_file $1`
	[ -n "$out" ] && mv -f $out $OUTFILE_CC
}

check_compiled() {
	out=`compile_file $1`
	if [ -n "$out" ]; then
		if !diff $out $OUTFILE_CC; then
			echo "Serious changes with $1 compiled to $out"
			exit 1
		fi
	fi
}
# }}}

#For script debugging.
DEBUG=0

TMP=~/tmp
[ -d $TMP ] || TMP=/tmp

#START 
new_patch

OUTFILE=`mktemp $TMP/tfile.XXXXXXXXXX`

[ -n $COMPILE_TEST ] && OUTFILE_CC=`mktemp $TMP/tfilecc.XXXXXXXXXX`

[ $DEBUG = 1 ] || cond_redir_to_null='> /dev/null'
find $PATHS -name '*.[ch]'| \
while read i; do
	sed -e 's/\<return\>(\(.*\))/return \1/' \
	 -e 's/\<if\> \?(\(.*\)){/if (\1) {/'  \
	 -e 's/\<if\>(\(.*\))/if (\1)/' \
	 -e 's/\<for\> \?(\(.*\)){/for (\1) {/' \
	 -e 's/\<for\>(\(.*\))/for (\1)/' \
	 -e 's/\<while\> \?(\(.*\)){/while (\1) {/' \
	 -e 's/\<while\>(\(.*\))/while (\1)/' \
	 -e 's/^\([\t]*\) \{8\}/\1\t/' \
	 -e 's/^\([\t]*\) \{8\}/\1\t/' \
	 -e 's/^\([\t]*\) \{8\}/\1\t/' \
	 -e 's/^\([\t]*\) \{8\}/\1\t/' \
	 -e 's/^\([\t]*\) \{8\}/\1\t/' \
	 -e 's/^\([\t]*\) \{8\}/\1\t/' \
	 -e 's/^\([\t]*\) \{8\}/\1\t/' \
	 -e 's/^\([\t]*\) \{8\}/\1\t/' \
	 -e 's/^\([\t]*\) \{8\}/\1\t/' \
	 -e 's/^\([\t]*\) \{8\}/\1\t/' \
	 -e 's/^\([\t]*\) \{8\}/\1\t/' \
	 -e 's/^ \([a-z_]*:\)/\1/' \
	< $i > $OUTFILE
	# The tab substitution is repeated to act on multiple initial tabs.
	# PATCHES changes
	# The repeated line would become:
	# -e 's/^\([ +-]\)\([\t]*\) \{8\}/\1\2\t/' \
	# The last line would become:
	# -e 's/^\([ +-]\) \([a-z_]*:\)/\1\2/'

	if ! eval diff -u $i $OUTFILE $cond_redir_to_null; then
		save_compiled $i
		add_to_patch $i
		cat $OUTFILE > $i
		check_compiled $i
		[ $DEBUG = 1 ] && break
	fi
done
rm $OUTFILE
patch_refresh
# vim: set foldmethod=marker:
