#!/usr/bin/python3

from __future__ import print_function

import sys, os, re

class cache:
  buf = []
  minutes = []
  speed = {}
  def add(self, date, count, pid, time, status):
      self.buf.append((date, count, pid, time, status))
      minute = date[:16]
      if minute in self.speed:
        self.speed[minute] += 1
      else:
        self.speed[minute] = 1
      self.minutes.append(minute)
      if len(self.buf)>20:
        self.echo()
  def echo(self):
      date, count, pid, time, status = self.buf.pop(0)
      minute = self.minutes.pop(0)
      if minute not in self.minutes:
        add = '[%d/min]' % self.speed[minute]
      else:
        add = ''
      print("%s [%5s:%3ds] %2d %s %s %s" \
            % (date, pid, time, count, '='*count, status, add))
  def flush(self):
      while self.buf:
        self.echo()

conn = {}
time_sum = {}
status = {}

if len(sys.argv)>1:
  if sys.argv[1]=='-':
    logfile = sys.stdin
  else:
    logfile = open(sys.argv[1])
else:
  logfile = open('/var/log/sagator/sagator.log')

buffer = cache()
for line in logfile.readlines():
  line = line.strip().split(' ', 1)
  pid = line[0].strip(": ")
  if len(line)<2:
    continue
  if line[1].startswith('smtpd(): service started'):
    buffer.flush()
    print("RESTART!!!")
    conn = {}
  elif line[1].startswith('STATS: '):
    if pid not in time_sum:
      time_sum[pid] = 0.0
    time_sum[pid] += float(line[1].split(' ')[1])
    status[pid] = line[1].split(':', 2)[-1].strip()
  elif line[1].startswith('Connection from: '):
    conn[pid] = line
  elif line[1].startswith('smtpd(): Closing connection.'):
    if pid in conn:
      c = conn[pid][1].split(' ', 4)
      buffer.add(
        c[-1], len(conn), pid,
        time_sum.get(pid, 0), status.get(pid, None)
      )
      del conn[pid]
      if pid in time_sum:
        del time_sum[pid]
buffer.flush()
