#!/bin/sh
#
# ./action.sh $id $user new
# ./action.sh $id $user msg 'Message Text'
#
# ./action.sh $id $user vote contra
# ./action.sh $id $user vote pro
# ./action.sh $id $user vote delete
#
# ./action.sh $id $user status rejected
# ./action.sh $id $user status applied
# ./action.sh $id $user status opened
# ./action.sh $id $user status discarded

sendmail=/usr/sbin/sendmail
url=https://www.rocklinux.net/submaster/smadm.cgi
reply=rock-devel@rocklinux.org
list=rock-sm@rocklinux.org
me=submaster@rocklinux.org
subjprefix="[rock-sm] "

id="$1" user="$2" cmd="$3" opt="$4"
echo "$( date "+%Y-%m-%d %H:%M" ) $*" >> action.log

owner="$( cat data/$id.owner )"
unique="$( date "+%s.$$" )"

export QUERY_STRING="q=1&i=$id"
export REQUEST_METHOD="GET"
unset HTTP_COOKIE

if [ "$cmd" = "new" ]; then
	./rediff.sh data/$id.patch > /dev/null
	./votecheck.pl $id > /dev/null
fi

if [ "$cmd" = "vote" ]; then
	./votecheck.pl $id > /dev/null
fi

mailtxt() {
	echo "From: $me"; echo "To: $1"
	[ -n "$reply" ] && echo "Reply-To: $reply"
	if [ "$cmd" = new ]; then
		echo "Message-ID: <${id//\//}.$me>"
	else
		echo "Message-ID: <${id//\//}.$unique.$me>"
		echo "References: <${id//\//}.$me>"
	fi
	echo "Subject: $subjprefix${id//\//} $user $cmd ${opt:0:40}"; echo
	./smadm.cgi | grep -A99 ^Content-type | tail +2 | \
		w3m -T text/html -cols 77 -dump 2> /dev/null | \
		perl -pe 's/\s+$/\n/; s/  {$x}/ / if ($x=length($_)-75) > 0;'
	echo "$url?i=${id//\//}"
}

if [ -f "user/$user.email" ]; then
	reply="$reply, $( cat user/$user.email )"
fi
if [ -f "user/$owner.email" -a "$user" != "$owner" ]; then
	reply="$reply, $( cat user/$owner.email )"
fi

( mailtxt "$list" | $sendmail -f "$me" "$list" >/dev/null 2>/dev/null & )

if [ -f "user/$user.email" ]; then
	email="$( cat user/$user.email )"
	( mailtxt "$email" | $sendmail -f "$me" "$email" >/dev/null 2>/dev/null & )
fi
if [ -f "user/$owner.email" -a "$user" != "$owner" ]; then
	email="$( cat user/$owner.email )"
	( mailtxt "$email" | $sendmail -f "$me" "$email" >/dev/null 2>/dev/null & )
fi

exit 0

