#!/usr/bin/env python2.7

import sys, os, re
import argparse
import commands
import fnmatch
import glob
import platform
import subprocess
import time
import pprint
import shlex
import tempfile
import getpass
from random import randint

fake = 0
fake_str = ""
if fake: fake_str = "Would"

arch = None
timestamp = time.strftime("%Y_%m_%d_%H%M%S")
userid = getpass.getuser()

platform = platform.system()
if (platform == "Darwin"):
   arch = "i386-mac"
elif (platform == "Linux"):
   arch = "x86_64-linux"
else:
   print "Unrecognized platform = %s" % (platform)
   sys.exit(1)

verbose = False

programs_base = "/programs" + "/" + arch

RE_uc = re.compile(r'^[A-Z]')
RE_colon_dot_star = re.compile(r':.*')
RE_colon_eol = re.compile(r':$')
RE_colon = re.compile(r':')
RE_underscore = re.compile(r'_')
RE_rc_versions = re.compile(r'^setVersion')

RE_csh = re.compile(r'/csh$|/tcsh$')
RE_sh = re.compile(r'/sh$|/bash$')

RE_export = re.compile(r'^\+ [ ]*export ')
RE_unset = re.compile(r'^\+ [ ]*unset ')
RE_alias = re.compile(r'^\+ [ ]*alias ')
RE_versions = re.compile(r'^\+ .*other supported versions:')

parent_shell = os.environ['SHELL']

launch_csh = None
launch_sh = None
launch_shell = None

if (re.search(RE_sh,parent_shell)):
   launch_sh = True
   launch_csh = False
   launch_shell="/bin/sh"
elif (re.search(RE_csh,parent_shell)):
   launch_sh = False
   launch_csh = True
   launch_shell="/bin/csh"

# freesurfer_temp_dir = '/tmp/freesurfer'
freesurfer_temp_dir = os.environ['HOME'] + '/tmp'

debug_default = 0
verbose_default = False

def main():

   global debug
   debug = debug_default
   global verbose
   verbose = verbose_default
   global freesurfer_home
   freesurfer_home = ""
   global temp_file_list 
   temp_file_list = []
   global whoami
   whoami = sys.argv[0]

   parser1 = argparse.ArgumentParser(description="Parser for workon command line arguments")
   p1_exclude_group = parser1.add_mutually_exclusive_group()

   parser1.add_argument('-d', '-debug', '--debug', type=int, default=debug_default, help='echo level of debug output')
   parser1.add_argument('-v', '-verbose', '--verbose', action='store_true', default=verbose_default, help='echo verbose output')
   parser1.add_argument('-fs', '-fast_shell', '--fast_shell', action='store_true', default=False, help='add -f to shell exec and ignore loading user environment')

   ns1 = parser1.parse_args()

   if (ns1.verbose): print "Verbose output enabled"
   verbose = ns1.verbose

   if (ns1.debug > 0): print "Debug output enabled at level = %i" % ns1.debug
   debug = ns1.debug

   if (debug >= 2): 
      print "platform = %s" % platform
      print "parent shell = %s" % parent_shell
      print "launch shell %s" % (launch_shell)

   # if (verbose): print "Parser 1 name space arguments: %s" % (ns1)
   if (debug >= 1): print "Parser 1 name space arguments: %s" % (ns1)

   global shell_opt
   if (ns1.fast_shell is False):
      shell_opt = ''
   else:
      shell_opt = ' -f'
   
   all_app_version_list = ['freesurfer']

   if (debug >= 2): print "all apps to workon = %s" % all_app_version_list

   for thing in all_app_version_list:
      if (debug >= 2): print "App to workon: %s" % thing

   alias_list = []
   env_list = []

   app_name = "freesurfer"
   binary_to_stat = "freeview"

   # FREESURFER_HOME

   if (launch_sh):
      # this for the mac
      shell_init_file = '.bash_profile'
   elif (launch_csh):
      shell_init_file = '.cshrc'

   freesurfer_home = ''
   # Try the shell init files for a setting of FREESURFER_HOME
   if (launch_sh):
      grep_fshome_cmd = 'grep FREESURFER_HOME $HOME/' + shell_init_file + " | grep -v '#' | grep -v source | grep '=' | sed 's;^.*=;;'"
   elif (launch_csh):
      grep_fshome_cmd = 'grep FREESURFER_HOME $HOME/' + shell_init_file + " | grep -v '#' | grep -v source | awk '{print $3}'"

   grep_fshome_cmd_out = commands.getstatusoutput(grep_fshome_cmd) 
   if grep_fshome_cmd_out[0] == 0:
      if grep_fshome_cmd_out[1] != '':
         freesurfer_home=grep_fshome_cmd_out[1].strip()
         if (debug >= 1): print "freesurfer home from shell init file= %s" % (freesurfer_home)
      else:
         if (debug >= 1): print "Did not find FREESURFER_HOME in shell init file via cmd: %s" % (grep_fshome_cmd)

   # Otherwise try and get from what installer recorded on the system
   # Mac installer is currently broken though in that it apparently always records that
   # the install is to the Applications folder (even when you install to another location).
   if not freesurfer_home:
      if (platform == "Darwin"):
         freesurfer_home = get_mac_install_info(app_name,binary_to_stat)
      # elif (platform == "Linux"):
         # freesurfer_home = get_linux_install_info(app_name,binary_to_stat)


   if (freesurfer_home):
      if (debug >= 1): print "FREESURFER_HOME = %s" % freesurfer_home
      env_list.append("FREESURFER_HOME" + ' ' + freesurfer_home)
   else:
      print "ERROR: Environment variable FREESURFER_HOME not set. Please set in your shell init file or use the installer."
      sys.exit(1)

   # SUBJECTS_DIR
   # Allow shell init file to override default setting 

   subjects_dir = ""
   if (launch_sh):
      grep_subjdir_cmd = 'grep SUBJECTS_DIR $HOME/' + shell_init_file + " | grep -v '#' | grep -v source | grep '=' | sed 's;^.*=;;'"
   elif (launch_csh):
      grep_subjdir_cmd = 'grep SUBJECTS_DIR $HOME/' + shell_init_file + " | grep -v '#' | grep -v source | awk '{print $3}'"


   grep_subjdir_cmd_out = commands.getstatusoutput(grep_subjdir_cmd) 
   if grep_subjdir_cmd_out[0] == 0:
      if grep_subjdir_cmd_out[1] != '':
         subjects_dir=grep_subjdir_cmd_out[1].strip()
         env_list.append("SUBJECTS_DIR" + ' ' + subjects_dir)
         if (debug >= 1): print "subjects dir from shell init file= %s" % (subjects_dir)
      else:
         if (debug >= 1): print "Did not find SUBJECTS_DIR entry in shell init file via cmd: %s" % (grep_subjdir_cmd)


   # MNI_DIR
   # Allow shell init file to override default setting 
   # Cant override freesurfer env script with this

   if (launch_sh): init_script = "FreeSurferEnv.sh"
   if (launch_csh): init_script = "FreeSurferEnv.csh"
   extra_source_cmd_arg = freesurfer_home + '/' + init_script
   if (debug >= 2): print "freesurfer source command = %s" % extra_source_cmd_arg 

   if (all_app_version_list):

      app_title = "_".join(str(x) for x in all_app_version_list)
      freesurfer_version = ""
      if (debug >= 2): print "app_title = %s" % app_title

      if (platform == "Darwin"):
         mac_window(env_list,alias_list,app_title,freesurfer_version,extra_source_cmd_arg)
      elif (platform == "Linux"):
         linux_window(env_list,alias_list,app_title,freesurfer_version,extra_source_cmd_arg)
      else:
         print "Unknown platform to launch window for"
         sys.exit(1)
   else:
      if (debug >= 2): print "No apps as args to workon"


   if (debug):
      clean_temp_files(temp_file_list, clean=False)
      # Restore to using line above once no longer running in debig mode thru platypus created .app bundle
      # clean_temp_files(temp_file_list, clean=True)
   else:
      clean_temp_files(temp_file_list, clean=True)

   # clean_temp_files(temp_file_list, clean=True)

   if (debug >= 1): print "\n" + "python script (0) exits"

   sys.exit(0)


#=======================================
# FUNCTIONS FOR LAUNCHING WINDOWS/SHELLS
#=======================================


def mac_window(env_list_in,alias_list_in,app_title,app_rev,extra_cmd):

   freesurfer_string="freesurfer" + "_" + timestamp + "_"

   # PASS IN ANY ENVIRONMENT OR ALIAS SETTINGS TO SOURCE IN AN SHELL (ENVIRONMENT) SCRIPT
   envscript = envlist_to_envscript(env_list_in)
   if (debug >= 2):
      for item in envscript: print "OUTPUT ENV %s" % item

   aliasscript = aliaslist_to_aliasscript(alias_list_in)
   if (debug >= 2):
      for item in aliasscript: print "OUTPUT ALIAS %s" % item

   if not os.path.exists(freesurfer_temp_dir): os.mkdir(freesurfer_temp_dir, 0755)


   # parent apple script file
   # tf1 = tempfile.NamedTemporaryFile(mode='w+b', bufsize=-1, suffix='', prefix=freesurfer_string, dir=None, delete=False)
   # asfile = tf1.name
   asfile = '/tmp/fs_' + userid + '_asfile_' + timestamp
   FH_asfile = open(asfile,"w+b")

   # expect script file
   # tf2 = tempfile.NamedTemporaryFile(mode='w+b', bufsize=-1, suffix='', prefix=freesurfer_string, dir=None, delete=False)
   # expfile = tf2.name
   expfile = '/tmp/fs_' + userid + '_expfile_' + timestamp
   FH_expfile = open(expfile,"w+b")

   # environment script file
   # tf3 = tempfile.NamedTemporaryFile(mode='w+b', bufsize=-1, suffix='', prefix=freesurfer_string, dir=None, delete=False)
   # envfile = tf3.name
   # if (debug >= 2): print "fname = %s" % (envfile)
   envfile = '/tmp/fs_' + userid + '_envfile_' + timestamp
   if (debug >= 2): print "fname = %s" % (envfile)
   FH_envfile = open(envfile,"w+b")

   temp_file_list.append(asfile)
   temp_file_list.append(expfile)
   temp_file_list.append(envfile)

   # GENERATE EXPECT SCRIPT
   # write for either csh or sh (whichever one is expected), e.g., csh
   """
   #!/usr/bin/env expect

   spawn csh
   expect {
   $prompt { 
      send "source $env_script $hostname\n"
      expect $prompt }
   }
   interact

   """

   app_title_split = re.sub(RE_underscore,' ',app_title)
   freeview_app = freesurfer_home + '/' + 'Freeview.app'

   if debug or verbose:
      # exp_0 = '#!/usr/bin/env expect -df'
      exp_0 = '#!/usr/bin/env expect -f'
   else:
      exp_0 = '#!/usr/bin/env expect -f'
   exp_1 = 'cd'
   # do not turn off any output if debug or verbose
   if debug or verbose:
      # exp_2 = '#'
      exp_2 = 'log_user 0'
   else:
      exp_2 = 'log_user 0'
   if (launch_sh):
      exp_3 = 'spawn /bin/sh' + shell_opt
      exp_P = 'set prompt "$ "'
   elif (launch_csh):
      exp_3 = 'spawn /bin/csh' + shell_opt
      exp_P = 'set prompt "% "'
   # exp_4 = 'expect {'
   # exp_5 = '  $prompt {'
   # exp_6 = '    send ' + '"' + 'source ' + envfile + '\\n' + '"'
   # exp_7 = '    expect $prompt ' + '\\n' '}'
   # exp_8 = '} > /dev/null'
   # exp_8 = '}'
   exp_4 = 'expect $prompt '
   exp_5 = 'send ' + '"' + 'source ' + envfile + '\\n' + '"'
   exp_6 = 'expect $prompt '
   exp_7 = 'send ' + '"' + 'source ' + extra_cmd + '\\n' + '"'
   exp_8 = 'send ' + '"' + 'open ' + freeview_app + '\\n' + '"'
   # these extra expect statements for prompt will supress output from freesurfer init file
   # exp_X = 'expect $prompt '
   exp_9 = 'puts ' + '"' + 'Welcome to the FreeSurfer shell\\n' + '"'
   # exp_Y = 'expect $prompt '
   exp_A = 'interact'
   # exp_Z = 'expect $prompt '

   expscript = [exp_0, exp_1, exp_2, exp_3, exp_P, exp_4, exp_5, exp_6, exp_7, exp_8, exp_9, exp_A]



   # GENERATE APPLE SCRIPT 
   # Example Apple Script
   
   """
   tell application "Terminal"
      activate
      do script "source <script to exec shell and subsequently source environment>"
      set currWin to index of first window
      tell window currWin
         set custom title of first tab to "A Custom Title"
      end tell
   end tell
   on applicide()
      set myAppFile to path to me as string
      tell application "System Events"
         delete disk item myAppFile
      end tell
   end applicide
   """

   # pick a random background color, mac color as RGB int values, (R,G,B)
   white=('65535','65535','65535')
   light_blue=('53970','57311','62194')
   light_yellow=('65021','64250','56283')
   light_grey=('56026','56026','56026')
   light_purple=('56540','55512','61937')

   color_list = [white,light_blue,light_yellow,light_grey,light_purple]
   x = randint(1,len(color_list))
   (RGB_red, RGB_green, RGB_blue) = color_list[x-1]
   
   sc_1 = 'tell application' + ' ' + '"Terminal"'
   sc_2 = '   set default settings to settings set' + ' ' + '"Basic"'
   sc_3 = '   activate'
   sc_4 = '   do script' + ' ' + '"exec' + ' ' + expfile + '"'
   sc_5 = '   set currWin to index of first window'
   sc_6 = '   tell window currWin'
   sc_7 = '      set custom title of first tab to ' + '"' + app_title.upper() + ':' + app_rev + '"'
   sc_8 = '      set position to {50, 50}'
   # sc_9 = '      set size to {1150, 850}'
   sc_9 = '      set size to {900, 400}'
   # sc_A = '      set font size to {12}'
   sc_A = '      set font size to {14}'
   sc_B = '      set background color to {' + str(RGB_red) + ',' + str(RGB_green) + ',' + str(RGB_blue) + ',0}'
   sc_C = '   end tell'
   sc_D = '   set output to' + ' ' + '(' + '"' + 'Applescript (2) Waiting for' + ' ' + freeview_app + ' ' + 'to launch...' + '"' + ')' 
   sc_E = '   repeat until application' + ' ' + '"' + freeview_app + '"' + ' ' + 'is running'
   sc_F = '      delay 0.0'
   sc_G = '      copy output to stdout'
   sc_H = '   end repeat'
   sc_I = 'end tell'

   script = [sc_1, sc_2, sc_3, sc_4, sc_5, sc_6, sc_7, sc_8, sc_9, sc_A, sc_B, sc_C, sc_D, sc_E, sc_F, sc_G, sc_H, sc_I]
   
   # mac_run_term_cmd = "osascript" + " " + asfile
   mac_run_term_cmd = "osascript -sh -so" + " " + asfile
   if (debug >= 1):  print "Running: %s\n" % (mac_run_term_cmd)

   # Use with to ensure file writes are saved and closed before going on to next file
   # (close statement should not be needed)

   # open and write parent apple script file
   with open(asfile, 'w') as FH_asfile:
      FH_asfile.writelines("%s\n" % item for item in script)

   # open and write expect script file
   with open(expfile, 'w') as FH_expfile:
      FH_expfile.writelines("%s\n" % item for item in expscript)

   # open and write environment script file
   with open(envfile, 'w') as FH_envfile:
      FH_envfile.writelines("%s\n" % item for item in envscript)

   with open(envfile, 'a') as FH_envfile:
      FH_envfile.writelines("%s\n" % item for item in aliasscript)

   # chmod and wait for close before running the files

   os.chmod(asfile,0755) 
   if (debug >= 2): os.system("cat " + asfile)

   os.chmod(expfile, 0775)
   if (debug >= 2): os.system("cat " + expfile)
   # if (debug >+ 2): os.system("ls -l " + expfile)

   os.chmod(envfile, 0775)
   if (debug >= 2): os.system("cat " + envfile)
   # if (debug >= 2): os.system("ls -l " + envfile)

   if (debug >= 1): print ""
   if (debug >= 1): print "0)       applescript and exepct script generated by python script = %s" % (whoami)
   if (debug >= 1): print "1)           python script runs shell command to exec applescript = %s" % (asfile)
   if (debug >= 1): print "2) applescript launches terminal and runs generated expect script = %s" % (expfile)
   if (debug >= 1): print "3)   expect script sets env vars and runs freesurfer init script  = %s\n" % (envfile)

   shell_cmd_2(mac_run_term_cmd, logfile='')


def linux_window(env_list_in,alias_list_in,app_title,app_rev,extra_cmd):

   freesurfer_string="freesurfer" + "_" + timestamp + "_"

   envscript = envlist_to_envscript(env_list_in)
   if (debug >= 2):
      for item in envscript: print "OUTPUT ENV %s" % item

   aliasscript = aliaslist_to_aliasscript(alias_list_in)
   if (debug >= 2):
      for item in aliasscript: print "OUTPUT ALIAS %s" % item

   if not os.path.exists(freesurfer_temp_dir): os.mkdir(freesurfer_temp_dir, 0755)

   # environment settings for launch_sh
   tf1 = tempfile.NamedTemporaryFile(mode='w+b', bufsize=-1, suffix='', prefix=freesurfer_string, dir=None, delete=False)
   envfile = tf1.name
   if (debug >= 2): print "fname = %s" % (envfile)

   FH_envfile = open(envfile,"w+b")
   FH_envfile.writelines("%s\n" % item for item in envscript)
   FH_envfile.writelines("%s\n" % item for item in aliasscript)
   FH_envfile.close()
   os.chmod(envfile, 0775)
   if (debug >= 2): os.system("cat " + envfile)
   # if (debug >= 2): os.system("ls -l " + envfile)

   # parent script file
   tf2 = tempfile.NamedTemporaryFile(mode='w+b', bufsize=-1, suffix='', prefix=freesurfer_string, dir=None, delete=False)
   asfile = tf2.name

   # expect script file
   tf3 = tempfile.NamedTemporaryFile(mode='w+b', bufsize=-1, suffix='', prefix=freesurfer_string, dir=None, delete=False)
   expfile = tf3.name

   # write for either csh or sh (whichever one is expected)
   """
   #!/usr/bin/env expect -f

   spawn csh
   expect {
   % { 
     send "source /Users/robertd/env1_csh\n" }
   }
   interact
   """

   exp_0 = '#!/usr/bin/env expect'
   exp_1 = 'cd'
   if (debug == 0):
      # minimize output when debugging turned off
      exp_2 = 'log_user 0'
   else:
      exp_2 = '#'
   if (launch_sh):
      exp_3 = 'spawn sh' + shell_opt
   elif (launch_csh):
      exp_3 = 'spawn csh' + shell_opt
   exp_4 = 'expect {'
   if (launch_sh):
      exp_5 = '  $ {'
   elif (launch_csh):
      exp_5 = '  % {'
   exp_6 = '    send ' + '"' + 'source ' + envfile + '\\n' + '"' + ' ' + '}'
   exp_6_1 = '    send ' + '"' + 'source ' + extra_cmd + '\\n' + '"'
   exp_7 = '}'
   exp_8 = 'interact'

   expscript = [exp_0, exp_1, exp_2, exp_3, exp_4, exp_5, exp_6, exp_6_1, exp_7, exp_8]

   FH_expfile = open(expfile,"w+b")
   FH_expfile.writelines("%s\n" % item for item in expscript)
   FH_expfile.close()
   os.chmod(expfile, 0775)
   if (debug >= 2): os.system("cat " + expfile)
   if (debug >= 2): os.system("ls -l " + expfile)

   if (debug >= 1): print "1) parent script = %s" % (asfile)
   if (debug >= 1): print "2) expect script = %s" % (expfile)
   if (debug >= 1): print "3) environment script = %s\n" % (envfile)

   # Example Script

   title = '"' + app_title.upper() + ':' + app_rev + '"'   

   """
   xterm -hold -title <TITLE> -e <EXPECT SCRIPT>

   gnome-terminal --title <TITLE> -e <EXPECT SCRIPT> 

   """

   # sc_1 = 'xterm -hold -title ' + title + ' -e ' + expfile
   sc_1 = 'gnome-terminal --title ' + title + ' -e ' + expfile

   if (platform == "Linux") and (os.path.isfile('/etc/redhat-release')):
      os_cmd  = "cat /etc/redhat-release | awk '{print $4}'"
      os_cmd_out = commands.getstatusoutput(os_cmd) 
      if os_cmd_out[0] == 0:
         os_rev = os_cmd_out[1]
      else:
         print "command failed: %s" % (os_cmd)
         sys.exit(1)

      # If CentOS 7, remove use of unsupported --title in gnome-terminal command
      if re.search('^7\.',os_rev):
         if (debug >= 2): print "Changing Linux terminal command for OS rev = %s" % os_rev
         sc_1 = 'gnome-terminal' + ' -e ' + expfile

   script = [sc_1]

   FH_asfile = open(asfile,"w+b")
   # if (debug >= 2): os.system("ls -l " + asfile)
   FH_asfile.writelines("%s\n" % item for item in script)
   FH_asfile.close()
   os.chmod(asfile,0755) 
   if (debug >= 2): os.system("cat " + asfile)
   if (debug >+ 2): os.system("ls -l " + asfile)

   run_term_cmd = "sh" + " " + asfile
   if (debug >= 1):  print "Running: %s\n" % (run_term_cmd)
   temp_file_list.append(asfile)
   temp_file_list.append(expfile)
   temp_file_list.append(envfile)
   shell_cmd_2(run_term_cmd, logfile='')



def envlist_to_envscript(envlist_in):

   envscript_out = []
   # ensure starting in $HOME - FIX ME: probably a better way to do this
   if (platform == "Linux"): envscript_out.append("cd $HOME")
   for item in envlist_in:
      (var,value) = item.split(' ')
      if launch_sh:
         envscript_out.append("export" + ' ' + var + '=' + value)
      elif launch_csh:
         envscript_out.append("setenv" + ' ' + var + ' ' + value)
      else:
         print "No shell specified for target environment"
         sys.exit(1)

   # if ( len(envlist_in) != len(envscript_out)):
   # +1 for cd $HOME
   if (platform == "Linux"):
      input_length = (len(envlist_in))+1
   else:
      input_length = len(envlist_in)

   if ( input_length != len(envscript_out)):
      print "Length error creating env var script"
      if (debug >= 1): print "input env list is length %i" % len(envlist_in)
      if (debug >= 1): print "output env script is length %i" % len(envscript_out)
      sys.exit(1)

   return envscript_out


def aliaslist_to_aliasscript(aliaslist_in):

   aliasscript_out = []
   for item in aliaslist_in:
      (var,value) = shlex.split(item)
      # alias string should be double quoted - maybe better to use index
      q1_index = item.index('"')
      value2 = item[q1_index:]
      if value2.startswith('"') and value2.endswith('"'):
          if (debug >= 3): print "alias via index looks OK: %s" % value2
          value = value2
      if (not value.startswith('"')) and (not value.endswith('"')):
         print "Error for alias: %s" % var
         print "Double quotes not found at start and end of string: %s" % value
         sys.exit(1)

      if launch_sh:
         aliasscript_out.append("alias" + ' ' + var + '=' + value)
      elif launch_csh:
         aliasscript_out.append("alias" + ' ' + var + ' ' + value)
      else:
         print "No shell specified for target environment"
         sys.exit(1)

   if ( len(aliaslist_in) != len(aliasscript_out)):
      print "Length error creating alias var script"
      if (debug >= 1): print "input alias list is length %i" % len(aliaslist_in)
      if (debug >= 1): print "output alias script is length %i" % len(aliasscript_out)
      sys.exit(1)

   return aliasscript_out


def get_mac_install_info(app,binary):
   pkg_names_cmd = "pkgutil --pkgs | grep -i" + " " + app
   pkg_names_out = commands.getstatusoutput(pkg_names_cmd)
   if pkg_names_out[0] == 0:
      # freesurfer installer info should record info we can use to set FREESURFE_HOME
      if pkg_names_out[1] != '':
         pkg_id = pkg_names_out[1]
         if (verbose): print "For %s using package id = %s" % (app,pkg_id)

      pkg_path_1 = ''
      pkg_path_1_cmd = "pkgutil --pkg-info" + " " + pkg_id + " " + '| grep -i "^volume"'
      pkg_path_1_out = commands.getstatusoutput(pkg_path_1_cmd)
      if pkg_path_1_out[0] == 0:
         if pkg_path_1_out[1] != '':
            pkg_path_1 = re.sub('^volume: ','',pkg_path_1_out[1]) 

      pkg_path_2 = ''
      pkg_path_2_cmd = "pkgutil --pkg-info" + " " + pkg_id + " " + '| grep -i "^location"'
      pkg_path_2_out = commands.getstatusoutput(pkg_path_2_cmd)
      if pkg_path_2_out[0] == 0:
         if pkg_path_2_out[1] != '':
            pkg_path_2 = re.sub('^location: ','',pkg_path_2_out[1]) 

      bin_binary_esc = '\/bin\/' + binary

      pkg_path_3 = ''
      pkg_path_3_cmd = "pkgutil --files" + " " + pkg_id + " " + '| grep -i ' + '"' + app + bin_binary_esc + '"'
      pkg_path_3_out = commands.getstatusoutput(pkg_path_3_cmd)
      
      if pkg_path_3_out[0] == 0:
         if pkg_path_3_out[1] != '':
            pkg_path_3 = re.sub(bin_binary_esc,'',pkg_path_3_out[1])

      test_path = pkg_path_1 + pkg_path_2 + '/' + pkg_path_3
      if not os.path.isdir(test_path):
         if (debug >= 1): print "Cannot stat candidate path for FREESURFER_HOME = %s" % test_path
         # For now, leave unset, and user will get message in terminal to set it
         # 
         # test_path = "/Applications/freesurfer"
         return ""
      else:
         if (debug >= 1): print "Per freesrufer installer info will set FREESURFER_HOME = %s" % test_path
         return test_path

   else:
      if (debug >= 1): print "Could not set FREESURFER_HOME from installer info"
      return ""

#=================
# MISC PROCESSING
#=================


def get_subdirs(root):
   dir_list = []
   for subdir in os.listdir(root):
      subdir_abspath = os.path.join(root, subdir)
      if os.path.isdir(subdir_abspath) == True:
         dir_list.append(subdir_abspath)
   return dir_list


def subdirs_with_files_pat_match(dir_list, file_wildcard, return_abspath=True):
   dirs_match = []
   for subdir in dir_list:
      if os.path.isdir(subdir):
         if (debug >= 3): print "Searching %s for wildcard %s" % (subdir, file_wildcard)
         # FIX ME - change wildcard of path to use a level argument
         for fnames in glob.glob(subdir + '/' + file_wildcard):
            if fnames:
               if (debug >= 1): print "%s/%s found" % (subdir,file_wildcard)
               if (return_abspath):
                  dirs_match.append(subdir)
               else:
                  dirs_match.append(os.path.basename(subdir))
      else:
         if (debug >= 1): print "Skipping invalid subdir %s" % subdir
         continue

   dirs_match.sort()
   return dirs_match


# run command and capturing stdout line by line
def runProcess(cmdline,subdir):    

   if (debug >= 2): print "Trying: (cd %s; %s)" % (subdir,cmdline)
   if os.path.isdir(subdir):
      os.chdir(subdir)
   else:
      print "subdirectory %s does not exist" % (subdir)
      return 1

   p = subprocess.Popen(cmdline, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
   return iter(p.stdout.readline, b'')


def shell_cmd_2(cmd, logfile=''):

      p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
      p.wait()
      result_str = p.stdout.read()
      if (debug): print "Shell command (1) done: %s " % (cmd)
      print result_str


def shell_cmd_2_nowait(cmd, logfile=''):

      # on the Mac, the shell cmd to run is osascript
      if logfile != '':
         orig_stdout = sys.stdout
         orig_stderr = sys.stderr
         sys.stdout = sys.stderr = open(logfile,'w',0)
         sys.stderr = open(logfile,'w',0)

      devnull = open(os.devnull, 'wb')

      p = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE)

      while True:
          out = p.stderr.read(1)
          if (out == '') and (p.poll() != None):
              break
          if (out != ''):
             sys.stdout.write(out)
             sys.stdout.flush()



def clean_temp_files(tfile_list, clean=False):
      if (clean and tfile_list):
      # if (tfile_list):
         for file in tfile_list:
            if (debug >= 1): print "Deleting script file %s" % file
            # print "Deleting script file %s" % file
            os.unlink(file)
            if ( (not os.path.isfile(file)) and (debug >= 1) ): print "Deleted %s" % file


# non-blocking
def shell_cmd_NEWER(cmd, tfile_list='',logfile='', clean=False):

      print "BEFORE cmd"

      orig_stdout = sys.stdout
      orig_stderr = sys.stderr

      if (logfile != ''):
         sys.stdout = sys.stderr = open(logfile,'w',0)
         sys.stderr = open(logfile,'w',0)
      elif not (debug or verbose):
         sys.stdout = sys.stderr = open(os.devnull,'w')
         sys.stderr = open(os.devnull,'w')

      p = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE)
      while True:
          out = p.stderr.read(1)
          if out == '' and p.poll() != None:
              break
          if out != '':
             sys.stdout.write(out)
             sys.stdout.flush()

      if logfile != '':
         sys.stdout.close()
         sys.stderr.close()
         sys.stdout = orig_stdout
         sys.stderr = orig_stderr
         os.system("cat " + logfile)

      # if (clean and tfile_list):
      if (clean and tfile_list and (debug == 0)):
         for file in tfile_list:
            os.unlink(file)
            if ( (not os.path.isfile(file)) and (debug >= 1) ): print "Deleted %s" % file

      print "AFTER cmd"

if __name__ == '__main__':
   main()

 
