#!/bin/sh

WARNTIME=$(expr 30 \* 24 \* 60 \* 60) # seconds
TODAY=$(date +%s)
#TODAY=$(date -d '2013-04-03' +%s)
UPLOADERS=~/repo/conf/uploaders/*
#UPLOADERS=/tmp/test

EXPIRY=
ADDRESS=

set_key_data() {

    e=
    a=
    k=${1}
    EXPIRY=
    ADDRESS=
    IFS=':' read e a <<EOO
$(LC_ALL= LANG= gpg -k --with-colons $k|grep '^pub'|cut -d: -f7,10)
EOO

    [ -n "$e" ] && EXPIRY=$(date -d $e +%s)
    [ -n "$a" ] && ADDRESS=$a

}

about_to_expire() {
    [ -n "$EXPIRY" -a \( $(( $EXPIRY - $TODAY )) -le $WARNTIME \) ] || return 1;
}

expired() { 
    [ -n "$EXPIRY" -a \( $(( $EXPIRY - $TODAY )) -le 0 \) ] || return 1;
}

for f in $UPLOADERS; do
    while read first second third fourth k; do
	if [ \( "$first" = 'allow' \) \
	    -a \( "$second" = '*' \) \
	    -a \( "$third" = 'by' \) \
	    -a \( "$fourth" = 'key' \) \
	    -a \( -n "$k" \) ]; then
	    SUBJECT=
	    set_key_data $k
	    { about_to_expire || expired; } && gpg --refresh-keys $k
	    set_key_data $k
	    if expired; then
		SUBJECT='Your published Package Signing Key is expired'
	    elif about_to_expire; then
		SUBJECT='Your published Package Signing Key is about to expire'
	    fi
	    if [ -n "$SUBJECT" ]; then
		#echo "$ADDRESS: Subject: $SUBJECT"
		#cat <<EOM | gpg --encrypt -a --batch --trust-model always --recipient $k| /usr/sbin/sendmail "$ADDRESS"
		cat <<EOM | /usr/sbin/sendmail "$ADDRESS"
Subject: $SUBJECT

Please extend the expiration date and send the updated key to the keyserver.
Reply to this mail if you want us to remove your key from our list.

$(gpg -k $k)

Best regards
EOM
	    fi
	fi
    done <$f
done
