#!/usr/env/bin python

import sys, re, os, os.path, stat, getpass, shutil

def replaceAll(file, searchExp, replaceExp):
	shutil.move( file, file + "~" )
	destination = open( file, "w" )
	source= open( file + "~", "r" )
	for line in source:
		if searchExp in line:
			line = line.replace(searchExp,replaceExp)
		destination.write( line )
	source.close()
	destination.close()	

def chmod_ar(filename):
	if os.path.exists(filename):
		st = os.stat(filename)
		os.chmod(filename, st.st_mode | stat.S_IREAD \
			| stat.S_IRGRP | stat.S_IROTH)
		
def chmod_arx(filename):
	if os.path.exists(filename):
		st = os.stat(filename)
		os.chmod(filename, st.st_mode | stat.S_IEXEC | stat.S_IREAD \
			| stat.S_IXGRP | stat.S_IRGRP | stat.S_IXOTH \
			| stat.S_IROTH)

def grep(pattern, filename):
	results = list()
	
	if os.path.exists(filename):
		file = open(filename, "r")
		for line in file:
			if re.search(pattern, line):
				results.append(line)
	return results
	
def findbirch(BASE_DIR = '..'):
	grep_res = grep("BirchProps.homedir", os.path.join(BASE_DIR, 'local', 'admin', 'BIRCH.properties'))
	if len(grep_res) > 0:
		BIRCH = grep_res[0].split("=")[1].rstrip("\n\r ")
	else: # Deprecated
		birchdir = open(os.path.join(BASE_DIR, 'local', 'admin', 'birchdir.param'))
		BIRCH = birchdir.readline().rstrip("\n\r ")
		birchdir.close()
	return BIRCH

def birchhome(BIRCH):
	# Make sure that this script doesn't run in BIRCHDEV, which 
	# would clobber the master copy of BIRCH.
	if "BIRCHDEV" in BIRCH:
		print('>>> birchhome.py cannot be run in BIRCHDEV')
		print('>>> Doing so would clobber the master copy of BIRCH')
		sys.exit(1)
	else:
		if os.path.isdir(BIRCH):
			grep_res = grep("BirchProps.minibirch", os.path.join('..', 'local', 'admin', 'BIRCH.properties'))
			
			if len(grep_res) > 0 and grep_res[0].split("=")[1].lower() == "true":
				FILELIST = [
					os.path.join(BIRCH, 'admin', "cshrc.source"),
					os.path.join(BIRCH, 'admin', "profile.source"),
					os.path.join(BIRCH, 'admin', "add_to_cshrc"),
					os.path.join(BIRCH, 'admin', "add_to_login"),
					os.path.join(BIRCH, 'admin', "add_to_profile"),
					os.path.join(BIRCH, 'admin', "newuser.py"),
					os.path.join(BIRCH, 'admin', "newuser"),
					os.path.join(BIRCH, 'dat', 'fasta', 'fastgbs'),
					os.path.join(BIRCH, 'install-scripts', 'htmldir.param'),
					os.path.join(BIRCH, 'install-scripts', 'newuser.py'),
					os.path.join(BIRCH, 'dat', 'fasta', 'fastgbs'), 
					os.path.join(BIRCH, 'dat', 'XLandscape', 'XLand'),
					os.path.join(BIRCH, 'admin', 'launchers', 'birch.desktop'),
					os.path.join(BIRCH, 'admin.uninstall', 'cshrc.source'),
					os.path.join(BIRCH, 'admin.uninstall', 'profile.source')]
			else:	  
				FILELIST = [
					os.path.join(BIRCH, 'admin', 'cshrc.source'),
					os.path.join(BIRCH, 'admin', 'profile.source'),
					os.path.join(BIRCH, 'admin', 'add_to_cshrc'),
					os.path.join(BIRCH, 'admin', 'add_to_login'),
					os.path.join(BIRCH, 'admin', 'add_to_profile'),
					os.path.join(BIRCH, 'admin', 'newuser.py'),
					os.path.join(BIRCH, 'admin', 'newuser'),
					os.path.join(BIRCH, 'dat', 'fasta', 'fastgbs'),
					os.path.join(BIRCH, 'install-scripts', 'htmldir.param'),
					os.path.join(BIRCH, 'install-scripts', 'newuser.py'),
					os.path.join(BIRCH, 'dat', 'fasta', 'fastgbs'),
					os.path.join(BIRCH, 'dat', 'XLandscape', 'XLand'),
					os.path.join(BIRCH, 'admin', 'launchers', 'birch.desktop'),
					os.path.join(BIRCH, 'admin.uninstall', 'cshrc.source'),
					os.path.join(BIRCH, 'admin.uninstall', 'profile.source'),
					os.path.join(BIRCH, 'java', 'ArrayNorm', 'ArrayNorm.lax'),
				        os.path.join(BIRCH, 'java', 'Jalview', 'Jalview.lax'),
				        os.path.join(BIRCH, 'java', 'genographer', 'genograph.cfg'),
				        os.path.join(BIRCH, 'pkg', 'NCBI', '.ncbirc')
                                        ]
                         
                        # For reasons I can't fathom, the last element in FILELIST prints the Setting lcoation message 30 times
                        # to the output log. I don't know if this is executing 30 times, of if the line is getting echoed
                        # 30 times. In any case, the script seems to work. The problem could be in getbirch.jar.                
                        for filename in FILELIST:
                             if os.path.isfile(filename):
                                 print("Setting location of BIRCH home directory as " + BIRCH + " in " + filename)

                                     #replaceAll(os.path.join(BIRCH, filename), '/home/psgendb/BIRCHDEV', BIRCH)
                                     #chmod_ar(os.path.join(BIRCH, filename))
                                 replaceAll(filename, '/home/psgendb/BIRCHDEV', BIRCH)
                                 chmod_ar(filename)

			# special cases - where execute permissions are required
			chmod_arx(os.path.join(BIRCH, 'admin', 'newuser'))
			chmod_arx(os.path.join(BIRCH, 'admin', 'newuser.py'))
			chmod_arx(os.path.join(BIRCH, 'install-birch', 'makelinks.sh'))
			chmod_arx(os.path.join(BIRCH, 'admin', 'launchers', 'birch.desktop'))

			# Make sure that all directories in $BIRCH are world
			# readable and world executable
			chmod_arx(BIRCH)
                        for birchdir in ['admin','dat','doc','GenBank','install-scripts','java','labace','local','manl','pkg','python','public_html','script','tutorials']:
                            bdir = os.path.join(BIRCH,birchdir)
                            if (not os.path.islink(bdir)) and os.path.isdir(bdir) :
                                if os.access(bdir,os.W_OK) :
                                    chmod_arx(bdir)
			
			# Set the userid of the birchdb database administrator
			stdwrm = os.path.join(BIRCH, 'public_html', 'birchdb', 'wspec', 'passwd.wrm')
			if os.path.exists(stdwrm):
				replaceAll(stdwrm, 'psgendb', getpass.getuser())
				chmod_ar(stdwrm)
			
			# Set the userid of the local birchdb database administrator
			lworm = os.path.join(BIRCH, 'public_html', 'local', 'birchdb', 'wspec', 'passwd.wrm')
			if os.path.exists(lworm):
				replaceAll(lworm, 'psgendb', getpass.getuser())
				chmod_ar(lworm)
		else:
			print("No such directory: " + BIRCH + ". Exiting")
			sys.exit(1)

if __name__=="__main__":
	birchhome(findbirch())
