#!/System/Library/Frameworks/Python.framework/Versions/2.5/Resources/Python.app/Contents/MacOS/Python

import sys, os, shutil

############################################################################################################
#
# FUNCTIONS
#
#===========================================================================================================
def updateShebang(fn):
    f = file(fn, 'r')
    text = f.readline()
    if text[:2] == "#!":
        text = "#!%s\n" %(sys.executable)
    text += f.read()
    #text = text.replace(chr(13), '')
    f.close()
    # write back
    fw = file(fn, 'w')
    fw.write(text)
    fw.close()


############################################################################################################
#
# MAIN
#
#===========================================================================================================

if __name__ ==  "__main__":

    print '''
 +++  BioCASE 
 +++  Adapt file permissions and shebangs

chmod, change shebang to %s.
''' %(sys.executable)
    
    scriptDirs     = ['../www/', '.']
    suffices       = ['.cgi', '.py']
    writeDirs      = ['../config/', '../log/', '../cache/']
    writeExecDirs    = ['../www/configtool/']
    for d in writeDirs:
        d = os.path.abspath(d)
        print "setting write permissions for all users in directory %s" %d
        for root, dirs, files in os.walk(d):
            for name in files:
                f = os.path.join(root, name)
                print "  update %s" %f
                os.chmod(f, 0666)
            print "  -- update directories --"
            for name in dirs:
                f = os.path.join(root, name)
                print "  update %s" %f
                os.chmod(f, 0777)
            print "  update %s" %root
            os.chmod(root, 0777)
        
    for d in writeExecDirs:
        d = os.path.abspath(d)
        print "setting execution & write permission for all users in directory %s" %d
        for root, dirs, files in os.walk(d):
            for name in files:
                for suff in suffices:
                    if name[-len(suff):] == suff:
                        f = os.path.join(root, name)
                        print "  update %s" %f
                        os.chmod(f, 0777)
            for name in dirs:
                f = os.path.join(root, name)
                print "  update %s" %f
                os.chmod(f, 0777)
            print "  update %s" %root
            os.chmod(root, 0777)

    for d in scriptDirs:
        d = os.path.abspath(d)
        print "updating scripts in directory %s" %d
        for root, dirs, files in os.walk(d):
            for name in files:
                for suff in suffices:
                    if name[-len(suff):] == suff:
                        # change this script
                        f = os.path.join(root, name)
                        print "  update %s" %f
                        os.chmod(f, 0755)
                        updateShebang(f)

