#!/usr/bin/env python

import datetime, sys, os
import apt_pkg

class Updates:
    def __init__(self, readme = None):
        self.can_name = None
        self.history = {}
	self.max = 14

        if readme:
            f = open(readme)
            x = f.readline()

            def read_md5s(ind, x=x):
                while 1:
                    x = f.readline()
                    if not x or x[0] != " ": break
                    l = x.split()
                    if not self.history.has_key(l[2]):
                        self.history[l[2]] = [None,None]
                    self.history[l[2]][ind] = (l[0], int(l[1]))
                return x

            while x:
                l = x.split()

                if len(l) == 0:
                    x = f.readline()
                    continue

                if l[0] == "Canonical-Name:":
                    self.can_name = l[1]
                    x = f.readline()
                    continue

                if l[0] == "MD5-History:":
                    x = read_md5s(0)
                    continue

                if l[0] == "MD5-Patches:":
                    x = read_md5s(1)
                    continue

                x = f.readline()

    def dump(self, out=sys.stdout):
        out.write("Canonical-Name: %s\n" % (self.can_name))
	hs = self.history
        l = self.history.keys()
        l.sort()

	cnt = len(l)
	if cnt > self.max:
		for h in l[:cnt-self.max]:
			os.unlink("%s.diff" % (h))
			del hs[h]
		l = l[cnt-self.max:]

	out.write("MD5-History:\n")
        for h in l:
            out.write(" %s %7d %s\n" % (hs[h][0][0], hs[h][0][1], h))
	out.write("MD5-Patches:\n")
        for h in l:
            out.write(" %s %7d %s\n" % (hs[h][1][0], hs[h][1][1], h))
	

format = "%Y-%m-%d-%H%M.%S"
now = datetime.datetime.utcnow().strftime(format)
(outfile, newfile, oldfile) = sys.argv[1:4]

tmpfile = oldfile + ".tmp"
difffile = now + ".diff"

upd = Updates(outfile)

os.link(newfile, tmpfile)

def sizemd5(fn):
	size = os.stat(fn)[6]
	f = open(fn)
	md5sum = apt_pkg.md5sum(f)
	f.close()
	return (md5sum, size)

oldsizemd5 = sizemd5(oldfile)
newsizemd5 = sizemd5(tmpfile)

if newsizemd5 == oldsizemd5:
	os.unlink(tmpfile)
else:
	os.system("diff --ed %s %s > %s" % (oldfile, tmpfile, difffile))
	difsizemd5 = sizemd5(difffile)

	upd.history[now] = (oldsizemd5, difsizemd5)

	os.rename(tmpfile, oldfile)

	f = open(outfile, "w")
	upd.dump(f)
	f.close()
