#!/usr/bin/python2.2
import sys, os

def mail(s): return os.popen('mail -s "%s" djb-updates@aaronsw.com' % s, 'w')
location = "/var/www/notabug/2002/cr.yp.to//"
os.putenv("MAILUSER", "djbbot")
os.putenv("MAILHOST", "aaronsw.com")
os.putenv("MAILNAME", "djb notification bot")

for line in sys.stdin:
    if line.startswith(location) and ':' in line:
        name, result = line.split(':') # @@handle : in filename
        name = name.replace(location, "")
        if name == ".htaccess": continue
        if result == " download successful\n":
            if os.access(".cr.yp.to.bak/"+name, os.F_OK):
                x = mail("http://cr.yp.to/"+name+" updated")
                x.write(os.popen("./diff.sh "+name).read()) #@@handle funny names
            else:
                x = mail("http://cr.yp.to/"+name+" created")
                x.write(open("cr.yp.to/"+name).read())
            del x
            os.popen("cp -p cr.yp.to/"+name+" .cr.yp.to.bak/"+name) #@@ditto
            #@@ problems when creating new directories
        elif result == " not found on remote, deleted\n":
            x = mail("http://cr.yp.to/"+name+" deleted")
            x.write("Previous content was:\n\n")
            x.write(open(".cr.yp.to.bak/"+name).read())
            del x
        else:
            x = mail("http://cr.yp.to/"+name+" problem")
            x.write("Received message: "+result)
            del x
    else:
            x = mail("mirroring problem")
            x.write("Received message: "+line)
            del x

