#!/usr/bin/env python

import os

# For all interpreter scripts running python,
# replace first line by "#!/usr/bin/env python"
for filename in os.listdir('.'):
    # Only ordinary files
    if not os.path.isfile(filename):
        continue

    try:
        with open(filename, 'r+') as F:
            # Read at most 512 bytes, this should be more than enough.
            # If we don't find '\n' in the first 512 bytes, we most likely
            # have a binary file.
            L = F.readline(512)
            # Make sure we read a complete line
            if len(L) < 1 or L[-1] != '\n':
                continue
            # Is the first line "#!.../python"?
            if L.startswith("#!") and L.find("/python") >= 0:
                # Read the rest of the file
                script = F.read()

                # Write the file again with a proper interpreter line
                print "Making %s script relocatable"%filename
                F.seek(0)
                F.write("#!/usr/bin/env python\n")
                F.write(script)
                # Truncate everything which follows in this file
                F.truncate()
    except IOError:
        pass
