#!/usr/bin/env python
"""
CVStrac plugin to embed directed graphs using graphviz dot diagrams inside
wiki entries. Inspired by the TWiki Directed Graph plugin:
http://twiki.org/cgi-bin/view/Plugins/DirectedGraphPlugin

$Log: dot.py,v $
Revision 1.1  2006/12/05 17:52:44  majid
CVStrac dot article

Revision 1.1  2006/11/22 01:23:58  majid
Initial revision

"""
import sys, os, getopt, md5, popen2, time
try:
  from sqlite3 import dbapi2 as sqlite
except ImportError:
  from pysqlite2 import dbapi2 as sqlite

def attach(dbname, cid, png):
  db = sqlite.connect(dbname, isolation_level=None)
  # purge old generated dots after 60 days
  # to keep the database small (and avoid the problem
  # of left-over PNGs in the TWiki plugin
  db.execute("""delete from attachment
  where fname like '%.png' and user='__dot__' and
  date < cast(strftime('%s', 'now') as int) - 60*86400""")
  atn = None
  for row in db.execute("""select atn from attachment
  where user='__dot__' and fname=?""", (cid + '.png',)):
    atn = row[0]
  if atn is None:
    db.execute("""insert into attachment
    (tn, size, date, user, mime, fname, description, content) values
    (0, ?, cast(strftime('%s', 'now') as int), '__dot__', 'image/png', ?,
    'generated by {dot}', ?)""",
               (len(png), cid + '.png', buffer(png)))
    for row in db.execute("""select atn from attachment
    where user='__dot__' and fname=?""", (cid + '.png',)):
      atn = row[0]
  return atn

def main():
  opts, args = getopt.getopt(sys.argv[1:], '', ['name=', 'db='])
  opts = dict(opts)
  assert '--db' in opts
  content = sys.stdin.read()
  cid = md5.new(content).hexdigest()
  print >> sys.stderr, content

  fn = '/tmp/cvsdot%d' % os.getpid()
  f = open(fn, 'w')
  print >> f, content
  f.close()
  pout, pin, perr = popen2.popen3('dot -Tpng %s' % fn)
  output = pout.read()
  err = perr.read()
  os.remove(fn)

  if output and not err:
    atn = attach(opts['--db'], cid, output)
    print '<img src="attach_get/%d/%s.png">' % (atn, cid)
  else:
    print '<pre>'
    print err
    print '</pre>'

if __name__ == '__main__':
  main()
