#!/bin/python
#
#	usage: upchk [path ...]
#
import os, string
from sys import *
import getopt
from md5 import md5

def hexstr(s):
	h = string.hexdigits
	r = ''
	for c in s:
		i = ord(c)
		r = r + h[(i >> 4) & 0xF] + h[i & 0xF]
	return r

def md5sum(p):
	f=open(p)
	s=f.read()
	f.close()
	s=md5(s).digest()
	return hexstr(s)

def ismatch(args, path):
	for a in args:
		if a[-1] == "/":
			if path[:len(a)] == a:
				return 1
		else:
			if path == a:
				return 1
	return 0

args=argv[1:]
for a in args:
	if a[0] != "/":
		print "argments must be absolute paths"
		exit()
if args == []:
	args = None

dd=os.listdir("/wrap/plan9")
d=[]
for a in dd:
	d.append(int(a))
d.sort()
g={}
for a in d:
	f=open("/wrap/plan9/%d/md5sum"%a)
	lines = f.readlines()
	for c in lines:
		c=c[:-1]
		e=string.split(c)
		if args:
			if ismatch(args,e[0]) > 0:
				g[e[0]]=[a, e[1]]
		else:
			g[e[0]]=[a, e[1]]
	f.close()
	try:
		f=open("/wrap/plan9/%d/remove"%a)
	except:
		continue
	lines = f.readlines()
	for c in lines:
		c=c[:-1]
		if args:
			if ismatch(args,c) > 0:
				g[c]=[a, None]
		else:
			g[c]=[a, None]
	f.close()
k=g.keys()
k.sort()
for c in k:
	try:
		h=md5sum(c)
	except:
		if g[c][1]:
			print c, g[c][0], "# no such file"
		continue
	m=g[c][1]
	if m:
		if h != m:
			print c, g[c][0], "# not equal"
	else:
		print c, g[c][0], "# should be removed"

"""
OUTPUT FORMAT
file	wrap		# comment
term% upchk
/386/9pcdisk 985745432 # not equal
/386/9pcdisk.gz 985745432 # not equal
/lib/vgadb 989254626 # not equal
/mail/lib/rewrite 971556349 # not equal
/rc/bin/termrc 971556349 # not equal
/sys/src/9/bitsy/segment.h 985745432 # no such file
/sys/src/9/ip/tcp.c 989254626 # not equal
/sys/src/9/pc/devether.c 989254626 # not equal
/sys/src/9/pc/mkfile 985745432 # not equal
/sys/src/libthread/thread.c 988250913 # should be removed
/sys/src/mkfile 985745432 # should be removed
"""