#!/usr/bin/python
#
# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
# See LICENSE for details.

import errno, os, sys, string

copyright = '''\
# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
# See LICENSE for details.
'''

try:
    fn = sys.argv[1]
    fp = open(fn)
except IOError, e:
    if e.errno != errno.ENOENT:
        raise
    lines = []
else:
    lines = fp.readlines()
    fp.close()
print fn
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])
