#!/usr/bin/python

# ****************************************
# +++  BioCASE 
# +++  Adapt files to Windows systems
#
# change shebang to current python interpreter
#
# ****************************************


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()
	f.close()
	# write back
	fw = file(fn, 'w')
	fw.write(text)
	fw.close()

def adaptMetakitLib(metakitLibPath):
    '''Rename metakit shared objects to fit the current OS and python version.
    Needs the path to the metakit libraries.'''
    OS = sys.platform # win32, linux1, linux2, sunos5, darwin1, darwin6
    # rename metakit lib according to OS
    if OS.startswith("win"): 
        dll = os.path.join(metakitLibPath,"Mk4py.dll")
        dll23 = os.path.join(metakitLibPath,"Mk4py_py23.dll")
        dll24 = os.path.join(metakitLibPath,"Mk4py_py24.dll")
        # delete old one?
        if os.path.isfile(dll):
            os.unlink(dll)
        # copy new one
        if (sys.version.startswith('2.2') or sys.version.startswith('2.3') ):
            print "Using the metakit library compiled for Python 2.2 & 2.3 on Windows."
            shutil.copy(dll23, dll)
        else:
            print "Using the metakit library compiled for Python 2.4 on Windows."
            shutil.copy(dll24, dll)
    else:
        print "This script is for windows operating systems."
        print "But it seems that you are running %s." % sys.platform
        print "Aborted."
        sys.exit()
	
	
############################################################################################################
#
# MAIN
#
#===========================================================================================================

if __name__ ==  "__main__":

	print '''
 +++  BioCASE 
 +++  Adapt files to Windows systems

change shebang to current python interpreter %s.
''' %(sys.executable)
	
	adaptMetakitLib(os.path.abspath('../lib/biocase/configtool/utilities/metakit'))	
	scriptDirs = ['../www/', '.']
	suffices   = ['.cgi', '.py']
	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
						updateShebang(f)
		
