#! /usr/bin/env python 

# Check for mail and notify.
# Written by Jacob Mandelson.
# Copyright waived, this program is released to the public domain.

'''
New mail is indicated by $MAIL's mtime being later (ie, newer) than
both what it was when we last checked (so the mailbox's been changed)
and its atime (so the new mail hasn't been read, nor was the mailbox
last written out by the MUA).

To make this work on an fs mounted 'noatime', you can make opening
and closing the mail reader explicitly update the mbox's atime
with 'touch -a', such as with this shell function:

mutt() {
    touch -a $MAIL
    command mutt "$@"
    touch -a $MAIL
}
'''

import os
import stat
import sys
import time

interval = 60
message = "You have new mail.\r\n"  # This is the message zsh's MAILCHECK uses.
command = "zsh -c 'time ( show_subjects; echo )'"  # Run after announcing mail.

def main():
	mailfile = os.getenv("MAIL")
	if (mailfile == None):
		# Using sys.stderr.write instead of print(file=sys.stderr)
		# everywhere so it's compatible with both Python 2 & 3.
		sys.stderr.write("$MAIL must be set.\n")
		exit(1)

	old_mailtime = os.stat(mailfile)[stat.ST_MTIME]

	while True:
		time.sleep(interval)	
		newmail_st = os.stat(mailfile)
		new_mailtime = newmail_st[stat.ST_MTIME]
		if (new_mailtime > old_mailtime and
		    new_mailtime > newmail_st[stat.ST_ATIME]):
			sys.stderr.write(message)
			old_mailtime = new_mailtime
			os.system(command)

try:
 	main()
except KeyboardInterrupt:
	exit(0)
