#!/usr/bin/env python
import os
import sys
import cgi
import re
import json
import pickle
from datetime import datetime
from datetime import timedelta
form = cgi.FieldStorage()
print "Content-Type: application/json"
print ""
fr = datetime.strptime(form["date"].value + " " + form["from"].value, "%Y %m %d %H:%M")
to = datetime.strptime(form["date"].value + " " + form["to"].value, "%Y %m %d %H:%M")
logdir = "/var/log/httpd/"
l = fr + timedelta(7) # a week after
higher = "access_log-%04d%02d%02d"%(l.year, l.month, l.day)
lower = "access_log-%04d%02d%02d"%(fr.year, fr.month, fr.day)
logfiles = [fname for fname in os.listdir(logdir) if fname.startswith("access_log-") and lower <= fname and fname <=higher]
#logfiles.sort()
if not logfiles: logfiles.append('access_log')
#ipaddr = "172.29.119." + str(int(name)+150)
errlog = []
error_count = 0
lines = []
maildb = pickle.load(open("name.pickle"))
for fname in logfiles[-2:]:
with open(logdir + fname) as f:
line = [l for l in f.readlines() if "logonoff" in l]
line = [re.match(r'^([0-9.]*).*\[(\d+/\w+/\d+:\d+:\d+:\d+).*logonoff\?(o.*) HTTP', l) for l in line]
line = [l.groups() for l in line if l]
line = [(ip, datetime.strptime(date, '%d/%b/%Y:%H:%M:%S'), action)
for ip, date, action in line]
line = [[ip, date.strftime("%Y/%m/%d %H:%M")]+action.split(':')
for ip, date, action in line if fr <= date and date <= to]
line = [[ip, date, action, id_, maildb[id_]["no"], maildb[id_]["name"],
maildb[id_]["reading"], maildb[id_]["dep"]] for ip, date, action, id_ in line if id_ in maildb]
lines += line
json.dump(lines, sys.stdout)