#!/usr/bin/python
import errno, os, sys, string

copyright = '''\
This module is part of the Quotient project and is Copyright 2003 Divmod:
http://www.divmod.org/.  This is free software.  You can redistribute it
and/or modify it under the terms of version 2.1 of the GNU Lesser General
Public License as published by the Free Software Foundation.'''

try:
    fn = sys.argv[1]
    fp = open(fn)
except IOError, e:
    if e.errno != errno.ENOENT:
        raise
    lines = []
else:
    lines = fp.readlines()
    fp.close()

preamble = None
if lines and lines[0][:2] == '#!':
    preamble = lines.pop(0)

ext = os.path.splitext(fn)[1]
if ext == '.c' or ext == '.h':
    cpy = '/*\n'
    for line in string.split(copyright, '\n'):
        cpy = cpy + ' * ' + line + '\n'
    copyright = cpy + ' */\n'
else:
    cpy = ''
    for line in string.split(copyright, '\n'):
        cpy = (cpy + '# ' + line).strip() + '\n'
    copyright = cpy
    


# try to guess whether the file already has a copyright notice:
criteria_lines = map(string.strip, string.split(copyright, '\n')[1:4])

for line in criteria_lines:
    if not line in map(string.strip, lines):
        break
else:
    print "file seems to have a copyright notice, not adding!"
    sys.exit(1)
fp = open(sys.argv[1]+'.tmp', 'w')
if preamble is not None:
    fp.write(preamble)
fp.write(copyright)
fp.writelines(lines)
fp.close()
os.rename(sys.argv[1]+'.tmp', sys.argv[1])
