#!/usr/bin/env python                                                                                                  

import sys
import errno
import os
import platform

if sys.version_info < (2, 4):
    oldpython=True
else:
    import subprocess
    oldpython=False

__author__ = "beerli"
__date__ = "$Nov 26, 2010 3:10:04 PM$"

def find_os():
    return platform.system()

def mkdir_p(path):
    try:
        os.makedirs(path)
    except OSError,e:
        if errno.errocode[e.errno] == errno.EEXIST:
            pass
        else: raise
#    except OSError as exc: # Python >2.5
#        if exc.errno == errno.EEXIST:
#            pass
#        else: raise
                        

def main():
    myos = find_os()
    homedir = os.path.expanduser('~')
    mypath = os.path.dirname(os.path.realpath(__file__))
    arg = ['./findshell']
    if oldpython==True:
        (child_stdin, child_stdout) = os.popen2(arg, 'r', 1024)
        shell = child_stdout.read()
    else:
        myprocess = subprocess.Popen(arg,
                  	  	             shell=True,
                        	         stdout=subprocess.PIPE)
        shelllist = myprocess.communicate()
        shell = shelllist[0].rstrip()

    if myos == 'Darwin':
        (migshell,migkit) = os.path.split(mypath)
        print migshell
        print migkit
        if migkit == "migrate_kit":
            (ownpath,dummy) = os.path.split(migshell)
            app = True
        else:
            ownpath = mypath
            migshell = mypath+"/migrateshell.app"
            app = False
    else:
        # linux
        (migshell,migkit) = os.path.split(mypath)
        migkit = "migrate_kit"
        ownpath = mypath
        app = False
    
    print
    print "Current directory:       "+ownpath
    print "Migrateshell application:"+migshell
    print "Home directory           "+homedir
    print "To install MIGRATE for all users you need the administrator password for this machine."
    print "Administrator install so that all users on the machen can use MIGRATE: /usr/local/migrate"
    print "User install put the MIGRATE executable in the User's home directory: home_directory/opt/migrate"
    answer =""
    answer = raw_input("Are you an administrator? If YES press return,  otherwise press NO: ")
    if answer == '':
        if myos == 'Darwin':
            if os.path.exists(migshell):            
                os.system("sudo rsync -a "+migshell+"/* /Applications/migrateshell.app")
        else:
            if os.path.exists(migshell):
                linux=True
        if not os.path.exists("/usr/local/migrate/bin"):
            os.system("sudo mkdir -p /usr/local/migrate/bin")
            os.system("sudo mkdir -p /usr/local/migrate/share")
        if os.path.exists(mypath+"/migrate-n"):
            os.system( "sudo rsync -a "+mypath+"/migrate-n /usr/local/migrate/bin/")
        if os.path.exists(mypath+"/migrate-n-mpi"):
            os.system("sudo rsync -a "+mypath+"/migrate-n-mpi /usr/local/migrate/bin/")
        if os.path.exists(mypath+"/findcores"):
            os.system("sudo rsync -a "+mypath+"/findcores /usr/local/migrate/bin/")
            os.system("sudo chmod +x /usr/local/migrate/bin/findcores")
        if os.path.exists(mypath+"/fastmigrate-n"):
            os.system("sudo rsync -a "+mypath+"/fastmigrate-n /usr/local/migrate/bin/")
            os.system("sudo chmod +x /usr/local/migrate/bin/fastmigrate-n")
        found = False
        for path in os.environ.get('PATH', '').split(':'):
            if path == "/usr/local/migrate/bin":
                found=True
                break
        if found == True: 
            print "No insertion of execution path needed, because it is already present"
        else:
            if "bash" in shell:
                f = open(homedir+'/.bash_profile', 'r')
		for line in f:
		    if "###migrate" in line:
			sys.exit() 
		f.close()
                f = open(homedir+'/.bash_profile', 'a')
                f.write("###migrate (popgen.sc.fsu.edu) start Path addition\n")
                f.write("PATH=$PATH:/usr/local/migrate/bin\n")
                f.write("export PATH\n")
                f.write("###migrate (popgen.sc.fsu.edu) end Path addition\n\n")
                f.close()
            else:
                print "Not implemented yet"
    else:
        #installation in user's home directory
        #
        answer = raw_input("Confirm that you want to install MIGRATE into your home directory [YES, NO]\n")
        if answer.upper() != "YES":
            print "Goodbye"
            sys.exit()
            
        if myos == 'Darwin':
            if os.path.exists(migshell):
                if not os.path.exists(homedir+"/Applications"):
                    os.system("mkdir -p "+homedir+"/Applications")
                os.system("rsync -a "+migshell+"/* "+homedir+"/Applications/migrateshell.app")
        else:
            if os.path.exists(migshell):
                linux=True
        if not os.path.exists(homedir+"/opt/migrate"):
            os.system("mkdir -p "+homedir+"/opt/migrate/bin")
            os.system("mkdir -p "+homedir+"/opt/migrate/share")
        if os.path.exists(mypath+"/migrate-n"):
            os.system( "rsync -a "+mypath+"/migrate-n "+homedir+"/opt/migrate/bin/")
        if os.path.exists(mypath+"/migrate-n-mpi"):
            os.system("rsync -a "+mypath+"/migrate-n-mpi "+homedir+"/opt/migrate/bin/")
        if os.path.exists(mypath+"/findcores"):
            os.system("sudo rsync -a "+mypath+"/findcores /opt/migrate/bin/")
            os.system("sudo chmod +x /opt/migrate/bin/findcores")
        if os.path.exists(mypath+"/fastmigrate-n"):
            os.system("sudo rsync -a "+mypath+"/fastmigrate-n /opt/migrate/bin/")
            os.system("sudo chmod +x /opt/migrate/bin/fastmigrate-n")
        found = False
        for path in os.environ.get('PATH', '').split(':'):
            if path == homedir+"/opt/migrate/bin":
                found=True
                break
        if found == True: 
            print "No insertion of execution path needed, because it is already present"
        else:
            if "bash" in shell:
                f = open(homedir+'/.bash_profile', 'r')
		for line in f:
		    if "###migrate" in line:
			sys.exit() 
		f.close()
                f = open(homedir+'/.bash_profile', 'a')
                f.write("###migrate (popgen.sc.fsu.edu) start Path addition\n")
                f.write("PATH=$PATH:"+homedir+"/opt/migrate/bin\n")
                f.write("export PATH\n")
                f.write("###migrate (popgen.sc.fsu.edu) end Path addition\n\n")
                f.close()
            else:
                print "Not implemented yet"

        print "MIGRATE was installed in your home directory under ~/opt/migrate"
        print " to remove simply delete the migrate folder in ~/opt"


if __name__ == "__main__":
    main()
    
