#!/bin/sh

. patchfns 2>/dev/null ||
. /usr/lib/patch-scripts/patchfns 2>/dev/null ||
. $PATCHSCRIPTS_LIBDIR/patchfns 2>/dev/null ||
{
	echo "Impossible to find my library 'patchfns'."
	echo "Check your install, or go to the right directory"
	exit 1
}

check()
{
	bad=0

	patch_name=$(stripit $1)
	PATCH=patches/$patch_name.patch
	TXT=txt/$patch_name.txt
	if [ ! -f $TXT ]
	then
		echo $TXT is missing
		exit 1
	fi

	if grep -i 'From:\|Cc:\|Signed-off-by:' $TXT > /dev/null
	then
		if grep '<.*@.*>' $TXT > /dev/null
		then
			true;
		else
			echo email addresses in "$TXT" are mangled
			bad=1
		fi
	fi
	if [ $bad -eq 1 ]
	then
		exit 1
	fi
}

author()
{
	patch_name=$(stripit $2)
	TXT=txt/$patch_name.txt
	if [ ! -f $TXT ]
	then
		echo $TXT is missing
		exit 1
	fi
	author=""
	while read l
	do
		for x in $l
		do
			a=$(echo "$x" | sed -n -e 's/.*<\(.*@[^>]*\).*/\1/p')
			if [ x"$a" != x ]
			then
				if [ x"$author" == x ]
				then
					author=$a
				else
					author="$author,$a"
				fi
			fi
		done
	done < $TXT
	echo "$TXT has $author"
	eval $1=$author
}
	
send()
{
	patch_name=$(stripit $1)
	PATCH=patches/$patch_name.patch
	TXT=txt/$patch_name.txt
	if [ ! -f $TXT ]
	then
		echo $TXT is missing
		exit 1
	fi
	SUBJECT=$(head -2 $TXT | tail -1)
	author AUTHOR $1
	cc=""
	to=""
	for i in $(echo $CC $AUTHOR | sed -e 's/,/ /g')
	do
		if ! echo "$cc" "$TO" | grep "$i"
		then
			if [ x"$cc" = x ]
			then
				cc=$i
			else
				cc="$cc,$i"
			fi
			to=$to" -to $i"
		fi
	done
	if [ x"$cc" != x ]
	then
		cc="-cc $cc"
	fi
	n=$(printf $TEMPLATE $patch_nr)
	SUBJECT="[patch $n/$total_patches] $SUBJECT"

	echo makemail -to $TO $cc -from=$FROM -subject="$SUBJECT"
	echo smtpsend -server=$SMTP_SERVER -to $TO $to -from=$FROM

	if cat $PATCH | makemail -to $TO $cc -from=$FROM -subject="$SUBJECT" \
		-date="$(date -R)" | \
		smtpsend -server=$SMTP_SERVER -to $TO $to -from=$FROM
	then
		true
	else
		echo "smtpsend failed"
		exit 1
	fi

	echo Sent [$patch_nr/$total_patches] $i $TO $cc
}

add_to()
{
	if [ x"$TO" != x ]
	then
		if [ x"$CC" = x ]
		then
			CC="$1"
		else
			CC="$CC,$1"
		fi
	else
		TO="$1"
	fi
}

if [ x"$SMTP_SERVER" = x ]
then
	SMTP_SERVER=localhost:25
fi

if [ x"$EMAIL_ADDRESS" = x ]
then
	echo "You must set the EMAIL_ADDRESS environment variable to your email address"
	exit 1
fi
FROM=$EMAIL_ADDRESS

TO=""
CC=""
REALLY_TO=""
while echo $1 | grep @
do
	add_to $1
	shift
done

add_to $EMAIL_ADDRESS

patch_nr=1
total_patches=0

for i in $*
do
	check $i
	total_patches=$(expr $total_patches + 1)
done

if [ $total_patches -lt 10 ]
then
	TEMPLATE="%d"
elif [ $total_patches -lt 100 ]
then
	TEMPLATE="%02d"
elif [ $total_patches -lt 1000 ]
then
	TEMPLATE="%03d"
else
	TEMPLATE="%04d"
fi

for i in $*
do
	send $i
	if [ $patch_nr -ne $total_patches ]
	then
		sleep 2
	fi
	patch_nr=$(expr $patch_nr + 1)
done

