#! /bin/csh
#############################################################################
# $CSURF_DIR/FreeSurferEnv.csh: source to setup FreeSurfer csh/tsch path,env
#############################################################################
# 10/09/19 -- basic working (all architectures, clean path)
# 11/01/11 -- setenv FREESURFER_HOME $CSURF_DIR, report all other setenv's
# 11/04/08 -- 05: add another ld path: $CSURF_DIR/afni/lib/$onearch for motif
# 11/05/12 -- onearch -> getonearch
# 11/06/28 -- add $path: $CSURF_DIR/mni_autoreg/bin/$onearch
# 11/06/28 -- rm $path: $CSURF_DIR/local/bin/`uname -s`
# 11/06/28 -- add LD_LIBRARY_PATH: $CSURF_DIR/lib/$onearch
# 11/06/28 -- PERL5LIB,MNI_CONFIG_PATH -> $CSURF_DIR/mni_autoreg/perl,cfg
# 11/07/18 -- 07: only addpath FC7 LD_LIBRARY_PATH if latest incompat kernels
# 11/08/08 -- 08: only addpath FC7 LD_LIBRARY_PATH if latest and RH9 compile
# 11/12/01 -- default to subject/sessions in CSURF_DIR if missing
# 13/03/16 -- Linux: add local bitmap fonts to fontpath w/xset +fp
# 13/03/22 -- Linux: better LD_LIB paths
# 13/08/17 -- Linux: fix bug in no-bloat locfontdir, mv fonts lib/fonts
# 13/08/20 -- rm unused cleanup (while porting to bash)
# 13/08/20 -- translated to sh/bash -> FreeSurferEnv.sh
# 13/08/20 -- bail if {DY}LD_LIBRARY{N32}_PATH has spaces!
# 13/10/11 -- detect Ubuntu with /etc/issue, avoid Ubuntu-broken lsb_release
# 14/02/28 -- don't use local Mac fontpath to 10.9, but ready to change
# 14/03/06 -- add LD_LIBRARY_PATH all linux (missing 32bit for 64bit distros)
# 14/09/09 -- add Darwin libX11 ver10 to DYLD_LIBRARY_PATH for MGH nmovie
# 14/09/15 -- rm Darwin libX11 ver10 from DYLD_LIBRARY_PATH (wrote new nmovie.c)
# 15/10/14 -- v13: CSURF_LIBRARY_PATH fixes Mac OS X 10.11 nopass-env2subshell
# 17/07/18 -- commented-out attempt to run PPC on 10.6.8 (req incl 32bit Xll)
# 17/07/23 -- make old PPC afni bins work using incl libXm.4 (mk ln's vers=3)
# 18/10/25 -- linux now uses 75dpi helvetica fonts from Mac 10.6 (finally same)
# 19/02/06 -- if -e /opt/X11/lib/flat_namespace, add to Mac DYLD for afni
# 19/06/20 -- don't bork $PATH by manipulating $path when member has space!
# 20/10/07 -- fix lss,lsf,cds,cdf aliases to accept spaces in FUNCT../SUBJ..
# 21/06/29 -- don't alter LANG (broke start xterm on MacOS 10.15!)


#TODO: add paths into MGH freesurfer if FSURF_DIR defined

### report current shell (next works tcsh/bash, Darwin/Linux/IRIX)
echo ""
echo -n "FreeSurferEnv.csh (vers=15) requires csh/tcsh -- current shell: "
ps -p$$ | grep sh | awk '{print $4}'
echo ""
### next filter 10.8 DYLD warning error but won't work in other shell
#ps -p$$ |& grep -v dyld | grep sh | awk '{print $4}'     # won't work in sh
#ps 2>&1 -p$$ | grep -v dyld | grep sh | awk '{print $4}' # won't work in csh

### to source this file from anywhere, edit/comment-in next 2 lines to instdirs
#setenv CSURF_DIR /usr/local/csurf          # or e.g., setenv CSURF_DIR ~/csurf
#setenv FSURF_DIR /usr/local/freesurfer     # or Mac: /Applications/freesurfer
### *or* "setenv CSURF_DIR /your/install/dir" before source'ing

#############################################################################
### try to prevent execute
if ("$0" =~ "*FreeSurferEnv.csh" || "$0" =~ "*FreeSurferEnv.csh8.5") then
  echo "FreeSurferEnv.csh: ### source file (exec'ing it has no effect on env)"
  echo ""
  echo "use: source FreeSurferEnv.csh"
  echo ""
  exit      # not goto skipout because (hopefully) was exec'd
endif

### if source local, set/reset CSURF_DIR to here, else use existing if set
if (-e ./FreeSurferEnv.csh || -e ./FreeSurferEnv.csh8.5) then
  if ($?CSURF_DIR) then
    echo "FreeSurferEnv.csh: CSURF_DIR reset to current dir"
  else
    echo "FreeSurferEnv.csh: CSURF_DIR set to current dir"
  endif
  setenv CSURF_DIR `pwd`
else   # source'ing from somewhere else, use CSURF_DIR if exists
  if (! $?CSURF_DIR) then
    echo "FreeSurferEnv.csh: ### edit 'setenv CSURF_DIR ...' line to inst dir"
    goto skipout
  else
    # OK -- CSURF_DIR set either above or already present in user's env
  endif
endif

### find specific architecture
if (! -e "$CSURF_DIR/bin/noarch/getonearch") then
  echo \
   "FreeSurferEnv.csh: ### can't find $CSURF_DIR/bin/noarch/getonearch (script)"
  goto skipout
endif
set onearch = `"$CSURF_DIR/bin/noarch/getonearch"`
if ($onearch == "unknown") then
  echo "FreeSurferEnv.csh: ### don't know this arch:"
  echo \
  'FreeSurferEnv.csh: ### $CSURF_DIR/bin/noarch/getonearch does not know arch:'
  uname -a
  unset onearch
  goto skipout
endif
set sys = `uname -s`   # for generic tests

### begin font path addition (if local xserver)
#set skipfontsflag = 1
if (! $?SSH_CLIENT && ! $?SSH_TTY) then
  set xsetfontmapflag = 0
  if ($sys == "Linux") set xsetfontmapflag = 1
  if ($sys == "Darwin") then
    set darwinrele = `uname -r`
    ## next in case XQuartz stops shipping bitmapped (OK to 2.7.7)
    #if ($darwinrele:r:r > 17) set xsetfontmapflag = 1  # 10.4=8 -> 10.13=17
    unset darwinrele
  endif
  echo "-----------------------------------------------------------------------"
  ### maybe force disable font path addition
  if ($?skipfontsflag) then
    if ($skipfontsflag) then
      unset skipfontsflag
      set xsetfontmapflag = 0
    endif
  endif
  if ($xsetfontmapflag) then  # was chk lsb_release, but Ubuntu missing/broken
    echo "csurf font changes:"
    if ($sys == "Linux") then
      #set csurffontdir = $CSURF_DIR/lib/fonts/ISO8859-2/75dpi # Fedora 7
      #set csurffontdir = $CSURF_DIR/lib/fonts/bitmap-fonts    # CentOS 5.9
      #set csurffontdir = $CSURF_DIR/lib/fonts/75dpi           # MacOSX 10.6
      set csurffontdir = $CSURF_DIR/lib/fonts/75dpi-helvetica  # MacOSX 10.6
    endif
    if ($sys == "Darwin") then
      #set csurffontdir = $CSURF_DIR/lib/fonts/75dpi           # MacOSX 10.6
      set csurffontdir = $CSURF_DIR/lib/fonts/75dpi-helvetica  # MacOSX 10.6
    endif
    echo " xset fp default (reset to default)"  # no bloat
    xset fp default
    echo " xset +fp $csurffontdir"
    xset +fp $csurffontdir
    echo " xset fp rehash"
    xset fp rehash
    unset csurffontdir
  else
    echo "[no X11 fontpath change]"
  endif
  unset xsetfontmapflag
endif

### begin setenv additions
echo "-----------------------------------------------------------------------"
echo "csurf setenv changes:"
echo " CSURF_DIR=$CSURF_DIR"

### next 2 must exist for FreeSurfer progs (user's .cshrc setenvs override)
if (! $?SUBJECTS_DIR)    setenv SUBJECTS_DIR     "$CSURF_DIR/subjects"
echo " SUBJECTS_DIR=$SUBJECTS_DIR"
if (! $?FUNCTIONALS_DIR) setenv FUNCTIONALS_DIR  "$CSURF_DIR/sessions"
echo " FUNCTIONALS_DIR=$FUNCTIONALS_DIR"

### add Tcl/Tk/Tix textlibs to setenv
setenv TCL_LIBRARY   "$CSURF_DIR/tcltktix/lib/noarch/tcl8.5"
echo " TCL_LIBRARY=$TCL_LIBRARY"
setenv TK_LIBRARY    "$CSURF_DIR/tcltktix/lib/noarch/tk8.5"
echo " TK_LIBRARY=$TK_LIBRARY"

### gather dirs for ${DY}LD_LIBRARY_PATH adjust (one :q-able list for each arch)
if ($onearch == "Darwin-ppc") then
  set addldpathlist = ( \
    "$CSURF_DIR/tcltktix/lib/$onearch" \
    "$CSURF_DIR/gsl/lib/$onearch" \
    "$CSURF_DIR/afni/lib/$onearch" \
  )
endif
if ($onearch == "Darwin-i386") then
  set addldpathlist = ( \
    "$CSURF_DIR/tcltktix/lib/$onearch" \
    "$CSURF_DIR/afni/lib/$onearch" \
  )
endif
if ($onearch == "Darwin-x86_64") then
  if (-e /opt/X11/lib/flat_namespace) then
    set addldpathlist = ( \
      "$CSURF_DIR/tcltktix/lib/$onearch" \
      /opt/X11/lib/flatnamespace \
    )
  else
    set addldpathlist = ( \
      "$CSURF_DIR/tcltktix/lib/$onearch" \
    )
  endif
endif
if ($onearch == "Linux-i386") then
  set addldpathlist = ( \
    "$CSURF_DIR/tcltktix/lib/$onearch" \
  )
endif
if ($onearch == "Linux-x86_64") then
  set addldpathlist = ( \
    "$CSURF_DIR/tcltktix/lib/$onearch" \
  )
endif
if ($onearch == "IRIX-mips" || $onearch == "IRIX64-mips") then
  set addldpathlist = ( \
    "$CSURF_DIR/tcltktix/lib/$onearch" \
  )
endif

### if {DY}LD_LIBRARY_PATH exists, pre-append (don't try to fix bloat)
# spaces OK existing/new, :q preserves previously quoted args
if ($sys == "Darwin") then
  echo " pre-appended to DYLD_LIBRARY_PATH (+ cp to CSURF_LIBRARY_PATH):"
  if ($?DYLD_LIBRARY_PATH) then
    set newldpathlist = "$DYLD_LIBRARY_PATH"
    foreach addldpath ( $addldpathlist:q )  # :q no unquote quoted path w/spaces
      set newldpathlist = "${addldpath}:${newldpathlist}"
      echo "  + $addldpath"
    end
  else
    set newldpathlist = ""
    foreach addldpath ( $addldpathlist:q )  # :q no unquote quoted path w/spaces
      if ("$newldpathlist" == "") then
        set newldpathlist = "${addldpath}"
      else
        set newldpathlist = "${addldpath}:${newldpathlist}"
      endif
      echo "  + $addldpath"
    end
  endif
endif
if ($sys == "Linux") then
  echo " pre-appended to LD_LIBRARY_PATH (+ cp to CSURF_LIBRARY_PATH):"
  if ($?LD_LIBRARY_PATH) then
    set newldpathlist = "$LD_LIBRARY_PATH"
    foreach addldpath ( $addldpathlist:q )  # :q no unquote quoted path w/spaces
      set newldpathlist = "${addldpath}:${newldpathlist}"
      echo "  + $addldpath"
    end
  else
    set newldpathlist = ""
    foreach addldpath ( $addldpathlist:q )  # :q no unquote quoted path w/spaces
      if ("$newldpathlist" == "") then
        set newldpathlist = "${addldpath}"
      else
        set newldpathlist = "${addldpath}:${newldpathlist}"
      endif
      echo "  + $addldpath"
    end
  endif
endif
if ($sys == "IRIX" || $sys == "IRIX64") then
  echo " pre-appended to LD_LIBRARYN32_PATH (+ cp to CSURF_LIBRARY_PATH):"
  if ($?LD_LIBRARYN32_PATH) then
    set newldpathlist = "$LD_LIBRARYN32_PATH"
    foreach addldpath ( $addldpathlist:q )  # :q no unquote quoted path w/spaces
      set newldpathlist = "${addldpath}:${newldpathlist}"
      echo "  + $addldpath"
    end
  else
    set newldpathlist = ""
    foreach addldpath ( $addldpathlist:q )  # :q no unquote quoted path w/spaces
      if ("$newldpathlist" == "") then
        set newldpathlist = "${addldpath}"
      else
        set newldpathlist = "${addldpath}:${newldpathlist}"
      endif
      echo "  + $addldpath"
    end
  endif
endif

### export
if ($sys == "Darwin") then
  setenv DYLD_LIBRARY_PATH "$newldpathlist"
  setenv CSURF_LIBRARY_PATH "$newldpathlist"
endif
if ($sys == "Linux") then
  setenv LD_LIBRARY_PATH "$newldpathlist"
  setenv CSURF_LIBRARY_PATH "$newldpathlist"
endif
if ($sys == "IRIX" || $sys == "IRIX64") then
  setenv LD_LIBRARYN32_PATH "$newldpathlist"
  setenv CSURF_LIBRARY_PATH "$newldpathlist"
endif
unset i currldpath currldpathlist addldpath addldpathlist newldpathlist

### add MNI setenv's (TODO: test moved work, else back to $CSURF_DIR/local)
setenv PERL5LIB        "$CSURF_DIR/mni_autoreg/perl" #local/lib/mni_autoreg/perl
setenv MNI_CONFIG_PATH "$CSURF_DIR/mni_autoreg/cfg"  #local/lib/mni_autoreg/cfg
### broke start xterm from xterm on MacOS 10.15 XQuartz (!?)
#setenv LANG  en_US    # RH9: unsetenv'd def=en_US.UTF-8 breaks perl shellwords

### AFNI
setenv AFNI_PLUGINPATH "$CSURF_DIR/afni/lib/$onearch"

### begin $path additions
echo "-----------------------------------------------------------------------"
echo "pre-appended to csh path:"

### add FreeSurfer, Tcl/Tk, AFNI bins to beginning of $path
#CSURF_DIR/local/bin/`uname -s` -> CSURF_DIR/mni_autoreg/bin/$onearch
set addpathlist = ( \
    "$CSURF_DIR/afni/bin/$onearch" \
    "$CSURF_DIR/mni_autoreg/bin/$onearch" \
    "$CSURF_DIR/tcltktix/bin/$onearch" \
    "$CSURF_DIR/bin/$onearch"  \
    "$CSURF_DIR/bin/noarch" \
)  # last ends up most front
### strip new members already there (maybe behind) (N.B.: only if no spaces)
if (`echo "$PATH" | grep -c " "` == 1) then
  echo "FreeSurferEnv.csh: ### some dirs on PATH have spaces!"
  # even concat to $path containing member w/spaces borks colons in $PATH!
  foreach addpath ( $addpathlist:q )  # :q to keep quoted spaces
    setenv PATH "${addpath}:${PATH}"  # don't mess w/lower case $path, quote
  end
else
  set currpathlist = ( $path )
  set newpathlist = ( )
  foreach currpath ( $currpathlist )
    foreach addpath ( $addpathlist )
      if ($currpath == $addpath) goto skippath
    end
    set newpathlist = ( $newpathlist $currpath )  # keep order
    skippath:
  end
  ### add new members to front
  foreach addpath ( $addpathlist )
    set newpathlist = ( $addpath $newpathlist)
    echo "  + $addpath"
  end
  set path = ( $newpathlist )
  unset currpathlist
endif
unset currpath addpath addpathlist newpathlist
unset sys

### aliases for command line navigation (spaces in env vars OK)
alias sdir 'setenv SUBJECTS_DIR \!*'               # SUBJECTS: sdir newsubjects
alias fdir 'setenv FUNCTIONALS_DIR \!*'            # FUNCTS: fdir newfuncts
alias lss cd\ \"\$SUBJECTS_DIR\"\;ls\ \-1\ \|grep\ \!\*   # lss mart (pattmatch)
alias lsf cd\ \"\$FUNCTIONALS_DIR\"\;ls\ \-1\ \|grep\ \!\* # lsf MS (pattmatch)
alias cds cd\ \"\$SUBJECTS_DIR\"/\!\*/scripts\;ls        # cds marty (spacesOK)
alias cdf cd\ \"\$FUNCTIONALS_DIR\"/\!\*/\*/scripts\;ls  # cdf 011325MS (ditto)
alias mp1 'mpeg_play -dither color -quiet -loop -controls off'

### backward
setenv DIAG      0x4040
setenv MRI_DIR   "$CSURF_DIR"     # tksurfer2000

### add FREESURFER_HOME for mri_surf2surf
setenv FREESURFER_HOME "$CSURF_DIR"

echo "-----------------------------------------------------------------------"
echo "other setenv changes (mostly bak compat):"
echo " FREESURFER_HOME=$FREESURFER_HOME (mri_surf2surf)"
echo " AFNI_PLUGINPATH=$AFNI_PLUGINPATH"
#echo " DIAG=$DIAG (for ancient surfer bins 2000)"
#echo " MRI_DIR=$MRI_DIR (for anvient surfer bins 2000)"
#echo " PERL5LIB=$PERL5LIB (MNI)"
#echo " MNI_CONFIG_PATH=$MNI_CONFIG_PATH (MNI)"
#echo " LANG=$LANG (for old perl fail on en_US.UTF-8)"
echo "-----------------------------------------------------------------------"
#echo "FreeSurfer0.8 from CSURF_DIR=$CSURF_DIR"
if ($?FSURF_DIR) then
  echo "MGH freesurfer from FSURF_DIR=$FSURF_DIR"
endif
if (`echo $PATH | grep -c " "` == 1) then
  echo \
    "FreeSurferEnv.csh: ### PATH dirs have space(s): MGH fs5.3 setup will fail!"
endif
echo ""

### check/warn if binaries for wrong architecture!
if (! -d "$CSURF_DIR/bin/$onearch") then
  echo "FreeSurferEnv.csh: ### binaries for $onearch not found!"
  echo "FreeSurferEnv.csh: ### perhaps wrong-architecture tarfile installed?"
endif
unset onearch

#############################################################################
### jump to here instead of exit (since source'ing! -> would exit curr shell)
skipout:

