# code adapted from virtualenv

from os import listdir
from os.path import abspath, dirname, join, isfile, isdir

htroot = abspath(dirname(__file__))
shebang = '#!'
shebangline = shebang + htroot + r'\python\python.exe'

print "Current hackable trac root  :   %s" % (htroot)
print "New shebang line for scripts: %s" % (shebangline)
print


def fixup_scripts(scripts_dir):

    if not isdir(scripts_dir):
        print "Invalid folder specified: %s" % (scripts_dir)
        return

    for filename in listdir(scripts_dir):

        filename = join(scripts_dir, filename)
        if not isfile(filename):
            # ignore subdirs, e.g. .svn ones.
            continue

        f = open(filename, 'rb')
        try:
            try:
                lines = f.read().decode('utf-8').splitlines()
            except UnicodeDecodeError:
                # This is probably a binary program instead
                # of a script, so just ignore it.
                continue
        finally:
            f.close()

        if not lines:
            print "[..] is empty   --> %s" % (filename)
            continue

        if not lines[0].strip().startswith(shebang):
            print "[..] no shebang --> %s" % (filename)
            continue

        if lines[0].strip() == shebangline:
            print "[ok] correct    --> %s" % (filename)
            continue

        lines = [shebangline] + lines[1:]
        f = open(filename, 'wb')
        f.write(('\n'.join(lines) + '\n').encode('utf-8'))
        f.close()
        print "[ok] processed  --> %s" % (filename)

fixup_scripts(htroot + r'\python\Scripts')
