#!/bin/bash
# $Id: headersBased-aacheck,v 1.1 2006/09/19 08:50:10 dom Exp $
# Shell script that takes a URI of an archive approval
# ...  challenge as single parameter
# ... and checks if the to-be approved mail has
# ... been signed correctly
# ... If so, approves automatically the archival
# To be invoked from .procmailrc (see aaa-procmailrc)

# Checkout of the code
AAA_CO=~/dev.w3.org/2004/archive-approval-automate

# logfile
LOG=~/.aaalog

# URI received in the mail
URI=$1
echo "Handling aa at $URI" >> $LOG

# Let's check the AA system knows the given id
if [ -z "`HEAD \"$URI\" >/dev/null && echo 1`" ]
then
 echo "AA returns 404 on '$URI'" >> $LOG
 exit 1
fi

ID=`echo -n $URI|sed -e "s_^http://www\.w3\.org/Mail/review?id=__"`

# extracting the message-id from the mail as displayed in the Web page
messageid="`xsltproc $AAA_CO/extract-mail.xsl $URI|grep '^Message-Id:'|head -1|cut -d ':' -f 2`"
# checking whether it was sent in the past 24 hours
recentness=$((`date +%s` - `date -d "\`grepmail -H -Y 'Message-Id:' \"$messageid\" mail/sent |grep '^Date:' |cut -d ':' -f 2-\`" +%s`))
if [ $recentness -lt 86400 ]
then
 # Using POST to approve the archival
 echo "Signature correct, proceeding with approval" >> $LOG
 if [ -z "`echo -n \"permission=yes&id=$ID\"|POST http://www.w3.org/Mail/review 1>/dev/null 2>> $LOG && echo 1`" ]
 then
   echo "POST failed" >> $LOG
   exit 1
 fi
else
 # Fail so that procmail pushes it forward
 echo "Aborting, incorrect signature or signature not found" >> $LOG
 exit 1
fi