#!/usr/bin/python
""" Print the folder, subject line, and time-since-receipt of the last message
in a procmail log file.  This is useful as a screen 'backtick' program,
allowing the status line or title bar to show the last received e-mail.

Example screenrc lines:
    backtick 1 30 30 lastmail
    hardstatus string "%H %n%?: %t%? %h  %1`"
"""
import os
import re
import sys
import time

### Customization section
# The location of the procmail logfile
FROM = os.path.expanduser("~/mail/from")
# A list of folders that are typically spam will not be listed as recent mail
BLACKLIST = ("spam", "superspam", "suspect", "inebraska")
### End customization section

folder_re = re.compile("^\s*Folder: (\S*)")
subject_re = re.compile("^\s*Subject: (.*)")
from_re = re.compile(r"From [a-z]*\s*(... ... .. ..:..:.. ....)")

INVALID, FOLDER, SUBJECT = range(3)
state = INVALID
folder = None
subject = None

def human_span(t):
    if t < 30: return "(less than a minute ago)"
    if t < 90: return "(about a minute ago)"
    return "(%d minutes ago)" % ((t+30)/60)

def sx(s):
    return "'" + s.replace("'", "'\\''") + "'"

for line in os.popen("tac 2>/dev/null " + FROM):
    if state == INVALID:
        m = folder_re.match(line)
        if m: 
            f = m.group(1)
            if f not in BLACKLIST:
                folder = f
                state = FOLDER
    elif state == FOLDER:
        m = subject_re.match(line)
        if m:
            subject = m.group(1)
            state = SUBJECT
    elif state == SUBJECT:
        m = from_re.match(line)
        if m:
            when = time.strptime(m.group(1))
            diff = time.time() - time.mktime(when)
            print "%s: %s %s" % (folder, subject, human_span(diff))
            break
else:
    print "No recent mail"            

#    Copyright 2009 Jeff Epler <jepler@unpythonic.net>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
