#! /bin/sh
#############################################################################
# $CSURF_DIR/FreeSurferEnv.sh: source to setup FreeSurfer sh/bash/zsh 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 from FreeSurferEnv.csh -> sh/bash version
# 13/08/20 -- bail if {DY}LD_LIBRARY{N32}_PATH *or* 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/06 -- rm set disabling sh append Linux LD_LIBRARY_PATH w/libjpeg62
# 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/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)
# 18/11/16 -- conv long-broken aliases to functs: sdir/fdir/lss/lsf/cds/cdf
# 18/11/28 -- fix bug in override font path additions
# 19/02/06 -- if -e /opt/X11/lib/flat_namespace, add to Mac DYLD for afni
# 19/06/20 -- allow $PATH bloat if members have spaces (hard to rm copies)
# 19/06/25 -- path spaces OK (stupid LIB/PATH parse code finally fixed w/IFS)
# 19/11/06 -- Mac zsh can directly source ('no bashisms' comes in handy!)
# 20/06/03 -- v16: fix zsh path parsing, detect zsh
# 20/06/08 -- rm empty path entry every new source
# 21/06/29 -- don't alter LANG (broke start xterm on MacOS 10.15!)

#TODO: could add paths into MGH freesurfer if FSURF_DIR defined (after csurf)

#############################################################################
### standard use of this script:
#cd ~/csurf     # or to wherever you installed csurf
#source FreeSurferEnv.sh

### or, to source file from anywhere, edit/comment-in next 2 lines to instdirs
#export CSURF_DIR=/your/install/dir/csurf
#export FSURF_DIR=/usr/local/freesurfer      # or Mac: /Applications/freesurfer
### or "export CSURF_DIR=/your/install/dir/csurf" # before source from anywhere

#############################################################################
### report current shell (next works tcsh/bash, Darwin/Linux/IRIX)
echo ""
echo -n "FreeSurferEnv.sh (vers=16) requires sh/bash/zsh -- current shell: "
myshell=`ps -p$$ | grep sh | awk '{print $4}'`
echo $myshell
echo ""
## check if zsh (for $PATH parsing)
foundzsh=0
if [ "$myshell" = "zsh" ]; then
  foundzsh=1;
  echo "FreeSurferEnv.sh: zsh detected (OK)"
fi
## bashrc fails b/c Mac doesn't pass $path, would have to guess abs ps/grep/awk
#foundzsh=0
## 1st: system source, 2nd: new xterm, 3rd: re-source in shell
#if [ "$0" = "-zsh" ] || [ "$0" = "zsh" ] || \
#   [ "$0" = "/Users/sereno/.zshrc" ]; then
#  foundzsh=1
#fi

### try to prevent execute w/o blocking source'ing from script
## N.B.: still broken: this prevents source inside script since $0=scriptname
#if [ $0 != "bash" ] && [ $0 != "sh" ] && [ $0 != "-bash" ] && \
#   [ $0 != "-sh" ]; then
#  echo "FreeSurferEnv.sh: ### source file (exec'ing it has no effect on env)"
#  echo ""
#  echo "use: source FreeSurferEnv.sh"
#  echo ""
#  exit      # not return because (hopefully) was exec'd
#fi

### if source local, set/reset CSURF_DIR to here, else use existing if set
if [ -e ./FreeSurferEnv.sh ] || [ -e ./FreeSurferEnv.sh8.5 ]; then
  if [ -z "$CSURF_DIR" ]; then
    echo "FreeSurferEnv.sh: CSURF_DIR set to current dir"
  else
    echo "FreeSurferEnv.sh: CSURF_DIR reset to current dir"
  fi
  export CSURF_DIR=`pwd`
else  # source'ing from somewhere else, use CSURF_DIR if exists
  if [ -z "$CSURF_DIR" ]; then
    echo "FreeSurferEnv.sh: ### edit 'export CSURF_DIR=...' line to inst dir"
    return    # we are sourcing: don't exit current shell
  else
    echo "FreeSurferEnv.sh: CSURF_DIR set to: $CSURF_DIR"
  fi
fi

### find specific architecture
if [ ! -e "$CSURF_DIR/bin/noarch/getonearch" ]; then
  echo \
   "FreeSurferEnv.sh: ### can't find $CSURF_DIR/bin/noarch/getonearch (script)"
  return
fi
onearch=`"$CSURF_DIR/bin/noarch/getonearch"`
if [ $onearch = "unknown" ]; then
  echo \
    "FreeSurferEnv.sh: ### \$CSURF_DIR/bin/noarch/getonearch doesn't know arch:"
  uname -a
  unset onearch
  return
fi
sys=`uname -s`   # for generic tests

### begin font path addition (if local xserver)
#skipfontsflag=1   # uncomment to force off for all arch
if [ -z "$SSH_CLIENT" ] && [ -z "$SSH_TTY" ]; then
  xsetfontmapflag=0
  if [ $sys = "Linux" ]; then xsetfontmapflag=1; fi
  if [ $sys = "Darwin" ]; then   # default X11 10.4 to 10.12 OK
    darwinrele=`uname -r`
    xsetfontmapflag=0
    ## next in case XQuartz stops shipping fonts (up to XQuartz 2.7.7 OK)
    #xsetfontmapflag=1
    #case $darwinrele in 8.*.*) xsetfontmapflag=0 ;; esac   # 10.4
    #case $darwinrele in 9.*.*) xsetfontmapflag=0 ;; esac   # 10.5
    #case $darwinrele in 10.*.*) xsetfontmapflag=0 ;; esac  # 10.6
    #case $darwinrele in 11.*.*) xsetfontmapflag=0 ;; esac  # 10.7
    #case $darwinrele in 12.*.*) xsetfontmapflag=0 ;; esac  # 10.8
    #case $darwinrele in 13.*.*) xsetfontmapflag=0 ;; esac  # 10.9
    #case $darwinrele in 14.*.*) xsetfontmapflag=0 ;; esac  # 10.10
    #case $darwinrele in 15.*.*) xsetfontmapflag=0 ;; esac  # 10.11
    #case $darwinrele in 16.*.*) xsetfontmapflag=0 ;; esac  # 10.12
    #case $darwinrele in 17.*.*) xsetfontmapflag=0 ;; esac  # 10.13
    #case $darwinrele in 18.*.*) xsetfontmapflag=0 ;; esac  # 10.14
    #case $darwinrele in 19.*.*) xsetfontmapflag=0 ;; esac  # 10.15
    unset darwinrele
  fi
  echo "-----------------------------------------------------------------------"
  ### maybe force disable font path addition
  if [ ! -z "$skipfontsflag" ]; then
    if [ $skipfontsflag = 1 ]; then
      unset skipfontsflag
      xsetfontmapflag=0
    fi
  fi
  if [ $xsetfontmapflag -eq 1 ]; then #was chk lsb_release, unreliable on Ubuntu
    echo "csurf font changes:"
    if [ $sys = "Linux" ]; then
      #csurffontdir=$CSURF_DIR/lib/fonts/ISO8859-2/75dpi # Fedora 7
      #csurffontdir=$CSURF_DIR/lib/fonts/bitmap-fonts    # CentOS 5.9
      #csurffontdir=$CSURF_DIR/lib/fonts/75dpi           # MacOSX 10.6 all
      csurffontdir=$CSURF_DIR/lib/fonts/75dpi-helvetica  # MacOSX 10.6 helv
    fi
    if [ $sys = "Darwin" ]; then
      #csurffontdir=$CSURF_DIR/lib/fonts/75dpi           # MacOSX 10.6 all
      csurffontdir=$CSURF_DIR/lib/fonts/75dpi-helvetica  # MacOSX 10.6 helv
    fi
    echo " xset fp default (reset to default)"  # no bloat re-run
    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]"
  fi
fi

### begin env additions
echo "-----------------------------------------------------------------------"
echo "csurf environment var changes:"
echo " CSURF_DIR=$CSURF_DIR"

### next 2 must exist for FreeSurfer progs (user's .bashrc exports override)
if [ -z "$SUBJECTS_DIR" ]; then export SUBJECTS_DIR=$CSURF_DIR/subjects; fi
echo " SUBJECTS_DIR=$SUBJECTS_DIR"
if [ -z "$FUNCTIONALS_DIR" ]; then export FUNCTIONALS_DIR=$CSURF_DIR/sessions;fi
echo " FUNCTIONALS_DIR=$FUNCTIONALS_DIR"

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

### gather dirs for ${DY}LD_LIBRARY_PATH adj (':' list sep so spaces in path OK)
# add Tcl/Tk/Tix and GSL (mgh) binary libs
addldpathlist="$CSURF_DIR/tcltktix/lib/$onearch:$CSURF_DIR/gsl/lib/$onearch"

## add path to missing 32/64bit binary libs for recent 64bit Ubuntu/Fedora/etc
if [ $sys = "Linux" ]; then
  ### next rm'd from my source tree (were in $CSURF_DIR/lib/$onearch)
  # tksurfer: libGLU.so.1, libjpeg.so.62
  # AFNI: libexpat.so.0, libfontconfig.so.1, libfreetype.so.6, libICE.so.6,
  #       libpng12.so.0, libSM.so.6, libXft.so.2, libXmu.so.6, libXpm.so.4,
  #       libXp.so.6, libXrender.so.1, libXt.so.6
  ## get kernel/version/distributor
  # get kern version, distributor (lsb_release sometimes missing)
  kern=`uname -r | cut -d \- -f 1 | cut -d . -f 1,2`
  vers=`uname -r | cut -d \- -f 1 | cut -d . -f 3`
  ldist="Unknown"
  ### N.B.: /etc/issue emptied on recent: rellist="/etc/issue *-release]"
  if [ -e /etc/issue ]; then # was lsb_release, but missing/broken on Ubuntu
    if [ "`grep CentOS /etc/issue`" != "" ]; then ldist="CentOS"; fi
    if [ "`grep Fedora /etc/issue`" != "" ]; then ldist="Fedora"; fi
    if [ "`grep Ubuntu /etc/issue`" != "" ]; then ldist="Ubuntu"; fi
    if [ "`grep Debian /etc/issue`" != "" ]; then ldist="Debian"; fi
    if [ "`grep Mint /etc/issue`" != "" ]; then ldist="Mint"; fi
    if [ "`grep Mageia /etc/issue`" != "" ]; then ldist="Mageia"; fi
    if [ "`grep OpenSUSE /etc/issue`" != "" ]; then ldist="OpenSUSE"; fi
  fi
  echo " [dist=$ldist]"  # not used yet
  addlibs=1    # all Linux
  rh9compile=0
  ### next stale since 2015
  #case $CSURF_DIR in *FreeSurfer0.8) rh9compile=1 ;; esac  # portable match
  #if [ $rh9compile ]; then
  #  if [ $kern = "2.4" ]; then addlibs=0; fi
  #  if [ $kern = "2.6" ] && [ $vers -lt 24 ]; then addlibs=0; fi
  #fi
  if [ $addlibs = 1 ]; then
    addldpathlist="$addldpathlist:$CSURF_DIR/afni/lib/$onearch"
  fi
  unset kern vers ldist addlibs rh9compile
fi

## missing binary libs for AFNI (omit: Mac 10.6 libiconv broke Mac 10.7 csh!!)
#if [ $onearch = "Darwin-x86_64" ]; then
#  addldpathlist=$addldpathlist:$CSURF_DIR/afni/lib/$onearch"
#fi
## make Darwin nmovie work, which requires libX11.6.dylib version 10.0
## N.B.: tksurfer etc still compiled against libX11 vers 9.0 for compat
## N.B.: no longer needed: tksurfer now compiled against libX11 vers 10.0 
#if [ $onearch = "Darwin-x86_64" ]; then
#  addldpathlist="$addldpathlist:$CSURF_DIR/lib/$onearch"
#fi

## make Darwin PPC afni bins work w/included Motif
if [ $onearch = "Darwin-ppc" ]; then
  addldpathlist="$addldpathlist:$CSURF_DIR/afni/lib/Darwin-ppc"
fi

### make AFNI work on newer XQuartz/MacOS
if [ $sys = "Linux" ] && [ -e /opt/X11/lib/flat_namespace ]; then
  addldpathlist="$addldpathlist:/opt/X11/lib/flatnamespace"
fi

### check if {DY}LD_LIBRARY_PATH exists
currldpathlist=""
if [ $sys = "Darwin" ]; then
  echo " pre-appended to DYLD_LIBRARY_PATH (+ cp to CSURF_LIBRARY_PATH):"
  if [ ! -z "$DYLD_LIBRARY_PATH" ]; then
    currldpathlist=$DYLD_LIBRARY_PATH
  fi
fi
if [ $sys = "Linux" ]; then
  echo " pre-appended to LD_LIBRARY_PATH:"
  if [ ! -z "$LD_LIBRARY_PATH" ]; then
    currldpathlist=$LD_LIBRARY_PATH
  fi
fi
if [ $sys = "IRIX" ] || [ $sys = "IRIX64" ]; then
  echo " pre-appended to LD_LIBRARYN32_PATH:"
  if [ ! -z "$LD_LIBRARYN32_PATH" ]; then
    #currldpathlist=$LD_LIBRARYN_PATH
    currldpathlist=$LD_LIBRARYN32_PATH
    #currldpathlist=$LD_LIBRARYN64_PATH
  fi
fi

### so zsh can run sh 'for' code for ldpath, path add (else only 1 'for' loop)
if [ $foundzsh -eq 1 ]; then
  set -o SH_WORD_SPLIT
fi

### make new colon separated (DY)LD LIBRARY path, allow path spaces
saveifs=$IFS
IFS=':'
newldpathlist=""
if [ "$currldpathlist" = "" ]; then
  # empty: make new
  i=1
  for addldpath in $addldpathlist; do
    if [ $i = 1 ]; then
      newldpathlist="${addldpath}"
    else
      newldpathlist="${addldpath}:${newldpathlist}"
    fi
    echo "  + $addldpath"
    i=`expr $i + 1`
  done
else
  # strip new members already there (maybe behind) (no goto)
  for currldpath in $currldpathlist; do
    found=0
    for addldpath in $addldpathlist; do
      if [ $currldpath = $addldpath ]; then found=1; fi
    done
    if [ $found = 0 ]; then
      if [ "$newldpathlist" = "" ]; then
        newldpathlist="${currldpath}"
      else
        newldpathlist="${newldpathlist}:${currldpath}"
      fi
    fi
  done 
  # add new members to front
  for addldpath in $addldpathlist; do
    if [ "$newldpathlist" = "" ]; then
      newldpathlist="${addldpath}"
    else
      newldpathlist="${addldpath}:${newldpathlist}"
    fi
    echo "  + $addldpath"
  done
fi
if [ $sys = "Darwin" ]; then
  export DYLD_LIBRARY_PATH="$newldpathlist"
  export CSURF_LIBRARY_PATH="$newldpathlist"
fi
if [ $sys = "Linux" ]; then
  export LD_LIBRARY_PATH="$newldpathlist"
  export CSURF_LIBRARY_PATH="$newldpathlist"
fi
if [ $sys = "IRIX" ]; then
  export LD_LIBRARYN32_PATH="$newldpathlist"
  export CSURF_LIBRARY_PATH="$newldpathlist"
fi
if [ $sys = "IRIX64" ]; then
  export LD_LIBRARYN32_PATH="$newldpathlist"
  export CSURF_LIBRARY_PATH="$newldpathlist"
fi
# cleanup
IFS=$saveifs
unset i currldpath currldpathlist addldpath addldpathlist newldpathlist saveifs

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

### AFNI
export AFNI_PLUGINPATH=$CSURF_DIR/afni/lib/$onearch

### begin $PATH additions (set -o SH_WORD_SPLIT still holds)
echo "-----------------------------------------------------------------------"
echo "pre-appended to sh \$PATH:"

### add FreeSurfer, Tcl/Tk, AFNI bins to begin colon-sep $PATH (spaces OK)
#CSURF_DIR/local/bin/`uname -s` -> CSURF_DIR/mni_autoreg/bin/$onearch
saveifs=$IFS
IFS=':'
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), keep order
currpathlist=$PATH
newpathlist=""
for currpath in $currpathlist; do
  found=0
  for addpath in $addpathlist; do
    if [ "$currpath" = "$addpath" ]; then found=1; fi
  done
  if [ $found = 0 ]; then
    if [ "$newpathlist" = "" ]; then
      newpathlist="${currpath}"
    else
      newpathlist="${newpathlist}:${currpath}"
    fi
  fi
done

### add new members to front
for addpath in $addpathlist; do
  newpathlist="${addpath}:${newpathlist}"
  echo "  + $addpath"
done
export PATH="$newpathlist"
# cleanup
IFS=$saveifs
unset currpath currpathlist addpath addpathlist newpathlist saveifs
unset onearch

### cleanup: go back to default zsh list behavior since we are source'ing
if [ $foundzsh -eq 1 ]; then
  set +o SH_WORD_SPLIT  # should check init state...
fi
unset myshell foundzsh

### helpful funcs (aliases) for command line navigation
## change SUBJECTS_DIR/FUNCTIONALS_DIR
sdir () {
  export SUBJECTS_DIR=$1
}
fdir () {
  export FUNCTIONALS_DIR=$1
}
## ls something in SUBJECTS_DIR/FUNCTIONALS_DIR w/implicit *patt* match
lss () {
  cd "$SUBJECTS_DIR"
  ls -1 | grep $1
}
lsf () {
  cd "$FUNCTIONALS_DIR"
  ls -1 | grep $1
}
## cd into SUBJECTS_DIR/FUNCTIONALS_DIR scripts dir (e.g., from list above)
cds () {
  cd "$SUBJECTS_DIR"/$1/scripts
  ls
}
cdf () {
  cd "$FUNCTIONALS_DIR"/$1/*/scripts
  ls
}

### backward
export DIAG=0x4040
export MRI_DIR=$CSURF_DIR     # tksurfer2000

### add FREESURFER_HOME for mri_surf2surf
export 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 ancient 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 [ ! -z "$FSURF_DIR" ]; then
  echo "MGH freesurfer from FSURF_DIR=$FSURF_DIR"
fi
if [ `echo $DYLD_LIBRARY_PATH | grep -c " "` = 1 ]; then
  echo \
    "FreeSurferEnv.sh: ### PATH dirs have space(s): MGH fs5.3 setup will fail!"
fi
echo ""

### check/warn if binaries for wrong architecture!
if [ ! -e "$CSURF_DIR/bin/$onearch" ]; then
  echo "FreeSurferEnv.sh: ### binaries for $onearch not found!"
  echo "FreeSurferEnv.sh: ### perhaps wrong tarfile is installed?"
fi
