# a simple algorithm to calculate a "version identifier" for a CVS working copy
# If the identifier of two trees differs, then the trees probably differ.
#
# The identifier refers to the basis tree for the working copy, rather than
# any local uncommitted changes.

import sys
import os
import md5

def _process_directory(directory, prefix, write):
    if not (os.path.isdir(directory) and
            os.path.isdir(os.path.join(directory, 'CVS'))):
        return
    
    fp = open(os.path.join(directory, 'CVS', 'Root'), 'rb')
    root = fp.read().strip()
    fp.close()
    fp = open(os.path.join(directory, 'CVS', 'Repository'), 'rb')
    repository = fp.read().strip()
    fp.close()

    write('===\n')
    write('Directory: %s\n' % prefix)
    write('Root: %s\n' % root)
    write('Repository: %s\n' % repository)
    write('\n')

    fp = open(os.path.join(directory, 'CVS', 'Entries'), 'rb')
    subdirs = []
    filenames = []
    for line in fp:
        parts = line.strip().split('/')
        if parts[0] == 'D' and len(parts) >= 2:
            subdirs.append(parts[1])
        if parts[0] == '' and len(parts) >= 3:
            filenames.append((parts[1], parts[2]))
    fp.close()
    filenames.sort()
    for name, rev in filenames:
        if prefix:
            name = '%s/%s' % (prefix, name)
        write('%s %s\n' % (name, rev))
    write('\n')
    subdirs.sort()
    for name in subdirs:
        if prefix:
            name_prefix = '%s/%s' % (prefix, name)
        else:
            name_prefix = name
        _process_directory(os.path.join(directory, name), name_prefix, write)

if __name__ == '__main__':
    if sys.argv[1:]:
        directory = sys.argv[1]
    else:
        directory = '.'
    
    md5sum = md5.new()
    _process_directory(directory, '', md5sum.update)
    print 'jhbuild-cvs-revid:%s' % md5sum.hexdigest()
