#!/usr/bin/python2

import os, time, gzip
from subprocess import Popen, PIPE

PREFIX = "/var/log/conntrack"

def process_data(ct):
    last_hour = ""
    log = None
    try:
      while True:
        row = ct.stdout.readline()
        ts, row = row.split(b"\t", 1)
        ts = float(ts.strip(b"[]"))
        t = time.strftime("%H:%M:%S", time.gmtime(ts))
        hour = time.strftime("%Y-%m-%d_%Hh", time.gmtime(ts//3600*3600))
        if last_hour!=hour:
          if log:
            log.close()
          logfn = os.path.join(PREFIX, hour+".ct.log.gz")
          print(logfn)
          log = gzip.open(logfn, "wb")
          last_hour = hour
        log.write(t.encode()+b" "+row)
        #print(t, hour, row.strip().decode())
    except KeyboardInterrupt:
      if log:
        log.close()

if __name__ == "__main__":
  ct = Popen("conntrack -E -o timestamp -e NEW,DESTROY".split(), stdout=PIPE)
  process_data(ct)
