#!/usr/bin/python

"""

	RemindMe Cron Job

	Reads the list of jobs in ~/.remindme/jobs and does any
	that are overdue

	date (dd/mm/yyyy HH:nn)
	subject 
	"message"

"""

fr = "reminder@rawsontetley.org"
to = "robin@rawsontetley.org"
smtphost = "mail.robsdomain"

import os
import sys
import time
import datetime
import smtplib

def toUnixDate(d):
    """
        Converts a Python date to a UNIX date
    """
    return time.mktime(d.timetuple())

def toPythonDate(d):
    """
        Converts a UNIX date to a Python date
    """
    return datetime.date.fromtimestamp(float(d))

def displayToPythonDate(d):
    """
        Converts a display date to a Python date
    """
    format = "%d/%m/%Y %H:%M"
    tt = time.strptime(d, format)
    return datetime.datetime(tt[0], tt[1], tt[2], tt[3], tt[4])

def pythonToDisplayDate(d):
    """
        Converts a Python date to a display date
    """
    format = "%d/%m/%Y %H:%M"
    return d.strftime(format)

# Read the list of jobs
newlist = []
f = open(os.environ["HOME"] + "/.remindme/jobs", "r")
while True:
	l = f.readline()
	if l.strip() == "": break
	l = l.strip()

	# Break down the line
	args = l.split("|")

	# Parse the date and time
	d = displayToPythonDate(args[0])
	subject=args[1]
	message=args[2]
	
	# If the job has passed, send the mail
	if toUnixDate(d) < toUnixDate(datetime.datetime.now()):
		
		# Construct the message
		msg = "From: " + fr + "\r\nTo: " + to + "\r\nSubject: " + subject + "\r\n\r\n" + message

		# Send the email
		smtp = smtplib.SMTP()
		smtp.connect(smtphost, 25)
		smtp.sendmail( fr, to, msg)

	else:
		# Otherwise, add the job to our list
		newlist.append(l)

f.close()

# Rewrite the list of jobs
f = open(os.environ["HOME"] + "/.remindme/jobs", "w")
for l in newlist:
	f.write(l + "\n")
f.close()

