#!/bin/sh

# don't run if this package is removed but not purged
if [ ! -f /usr/sbin/popularity-contest ]; then
	exit 0
fi

unset MAILFROM
unset MAILTO
unset MY_HOSTID
unset PARTICIPATE
unset SUBMITURLS
unset USEHTTP

# get configuration information
. /usr/share/popularity-contest/default.conf
. /etc/popularity-contest.conf

# don't run if MAILTO address is blank, or not configured to use HTTP POST!
if [ -z "$MAILTO" ] && [ "yes" != "$USEHTTP" ]; then exit 0; fi

# don't run if PARTICIPATE is "no" or unset!
[ "$PARTICIPATE" = "no" ] || [ -z "$PARTICIPATE" ] && exit 0

# keep old logs
cd /var/log
umask 022
savelog -c 7 popularity-contest >/dev/null
POPCON=/var/log/popularity-contest

run_popcon()
{
	# Set HOME to avoid bug #212013.
	HOME=/tmp su -pc "sh -c /usr/sbin/popularity-contest" nobody
}

do_sendmail()
{
	if [ -n "$MAILFROM" ]; then
		sendmail -oi -f "$MAILFROM" "$MAILTO"
	else
		sendmail -oi "$MAILTO"
	fi
}

# generate the popularity contest data

run_popcon > $POPCON

SUBMITTED=no

# try to post the report through http POST
if [ "$SUBMITURLS" ] && [ "yes" = "$USEHTTP" ]; then
    for URL in $SUBMITURLS ; do
	if setsid /usr/share/popularity-contest/popcon-upload \
	    -u $URL -f $POPCON -C 2>/dev/null ; then
		SUBMITTED=yes
	else
		logger -t popularity-contest "unable to submit report to $URL."
	fi
    done
fi

# try to email the popularity contest data

if [ yes != "$SUBMITTED" ] && [ -n "$MAILTO" ]; then
    if [ -x "`which sendmail 2>/dev/null`" ]; then
	# Sending compressed emails are disabled as the receiving end
	# isn't implemented yet.
	if false && [ -x "`which mime-construct 2>/dev/null`" ]; then
        	# Make compresssed email
		if [ -n "$MAILFROM" ]; then
			gzip -9 < $POPCON | mime-construct \
			    --type application/x-popcon-compressed \
			    --encoding base64 --file - \
			    --subject "popularity-contest submission" \
			    --to "$MAILTO" \
			    --header "From: <$MAILFROM>" \
			    --header "Sender: <$MAILFROM>" \
			    --output | do_sendmail
		else
			gzip -9 < $POPCON | mime-construct \
			    --type application/x-popcon-compressed \
			    --encoding base64 --file - \
			    --subject "popularity-contest submission" \
			    --to "$MAILTO" \
			    --output | do_sendmail
		fi
	else
            # Not able to make compressed email, send uncompressed
	    (
		if [ -n "$MAILFROM" ]; then
		    	echo "From: <$MAILFROM>"
			echo "Sender: <$MAILFROM>"
		fi
		echo "To: $MAILTO"
		echo "Subject: popularity-contest submission"
		echo "MIME-Version: 1.0"
		echo "Content-Type: text/plain"
		echo
		cat $POPCON
	    ) | do_sendmail
	fi
	SUBMITTED=yes
    else
	logger -t popularity-contest "unable to submit report using sendmail."
    fi
fi

if [ "yes" != "$SUBMITTED" ] ; then
	logger -t popularity-contest "unable to submit report."
fi
