# only redirect module from stderr to stdout in interactive mode
# to avoid breaking non interactive session (scp, sftp, etc)
if [[ $- =~ i ]]; then
   # set module command in accordance with active version
   if [ "$MODULES_USE_COMPAT_VERSION" = '1' ]; then
      _moduleraw() { eval `/usr/lib/modulecmd-compat bash $*`; }
   else
      _moduleraw() { eval `/usr/bin/tclsh /usr/lib/modulecmd.tcl bash $*`; }
   fi
   module() { _moduleraw $* 2>&1 ; }
   # export functions to get them defined in sub-shells
   export -f _moduleraw
   export -f module
else
   if [ "$MODULES_USE_COMPAT_VERSION" = '1' ]; then
      module() { eval `/usr/lib/modulecmd-compat bash $*`; }
   else
      module() { eval `/usr/bin/tclsh /usr/lib/modulecmd.tcl bash $*`; }
   fi
   export -f module
fi

# define function to switch between C and Tcl versions of Modules
switchml() {
   typeset swfound=1
   if [ "$MODULES_USE_COMPAT_VERSION" = '1' ]; then
      typeset swname='main'
      if [ -e /usr/lib/modulecmd.tcl ]; then
         typeset swfound=0
         unset MODULES_USE_COMPAT_VERSION
      fi
   else
      typeset swname='compatibility'
      if [ -e /usr/lib/modulecmd-compat ]; then
         typeset swfound=0
         MODULES_USE_COMPAT_VERSION=1; export MODULES_USE_COMPAT_VERSION
      fi
   fi

   # switch version only if command found
   if [ $swfound -eq 0 ]; then
      echo "Switching to Modules $swname version"
      source /usr/init/bash
   else
      echo "Cannot switch to Modules $swname version, command not found"
      return 1
   fi
}
export -f switchml

# setup ENV variables to get module defined in sub-shells (works for 'sh'
# and 'ksh' in interactive mode and 'sh' (zsh-compat), 'bash' and 'ksh'
# (zsh-compat) in non-interactive mode.
ENV=/usr/init/profile.sh; export ENV
BASH_ENV=/usr/init/bash; export BASH_ENV

# enable completion only in interactive mode
if [ ${BASH_VERSINFO:-0} -ge 3 ] && [[ $- =~ i ]] &&
   [ -r /usr/init/bash_completion ]; then
   source /usr/init/bash_completion
fi

MODULESHOME=/usr; export MODULESHOME

if [[ ! ":$PATH:" =~ ':/usr/bin:' ]]; then
   PATH=/usr/bin${PATH:+:}$PATH; export PATH
fi

manpath=`manpath 2>/dev/null`
if [[ ! ":$manpath:" =~ ':/usr/share/man:' ]]; then
   MANPATH=/usr/share/man${manpath:+:}$manpath; export MANPATH
fi

if [ "${MODULEPATH:-}" = '' ]; then
   if [ -r /usr/init/.modulespath ]; then
      MODULEPATH=`sed -n 's/[ 	#].*$//; /./H; $ { x; s/^\n//; s/\n/:/g; p; }' \
         /usr/init/.modulespath`; export MODULEPATH
   else
      MODULEPATH=; export MODULEPATH
   fi
fi

if [ "${LOADEDMODULES:-}" = '' ]; then
   LOADEDMODULES=; export LOADEDMODULES
fi

# load modulerc only if module environment is empty
if [ "$MODULES_USE_COMPAT_VERSION" != '1' -a -r /usr/init/modulerc -a "$MODULEPATH" = '' -a "$LOADEDMODULES" = '' ]; then
   module source /usr/init/modulerc
fi
