#! /bin/sh
## "@(#) $Id: dfos.cleanLD_LIBRARY_PATH,v 1.4 2008/02/26 15:11:31 jpritcha Exp $"

# PURPOSE:      clean $LD_LIBRARY_PATH
# AUTHOR:       John Pritchard / ESO
# VERSIONS:     1.0 -- creation, for usage on (old systems and) new DFO blades (2008-02-26)
#		1.1 -- improved clean up and path recognition (2009-02-12)
# OUTPUT:       none
# CONFIG:       none
# NOTE:         should be called in .qcrc, at its very end, as:
#               `dfosCleanPath`
#               dfosCleanPath -h will give the options.
# =========================================================================

TOOL_VERSION="1.1"
################################################################################
## Definition of functions
usage() {
  printf "\
Usage: ${execName} [-h|Dvnq]

  -h|--help: help
  -D|--debug: debug
  -n|--dryRun: dry-run
  -q|--quiet: quiet
     -q Only Warnings and Errors are written out (to stderr)
     -q -q increases quietness, only Errors are written out (to stderr)
     -q -q -q increases quietness, NO output to stdout or stderr
  -v|--verbose: verbose

This script 'cleans' the LD_LIBRARY_PATH of entries already included in
/etc/ld.so.conf or in .conf files in /etc/ld.so.conf.d in order to achieve
the full performance of the DFO blade and eventually the QC cluster systems.

To use correctly add the following TWO lines to the very END of your
.qcrc file

# Cleanup LD_LIBRARY_PATH enviroment variable
\`${execName}\`

Note that the backquotes ('\`') are important, without these it will simply
echo what should be done, but not actually change anything.

It is also important to NOT give any command line options when used in
.qcrc, as these may have unpredictable influence on the way it behaves.
They can of course be used ineractively to see what it is doing and to
see the result of running it.

Remember, that any path in LD_LIBRARY_PATH will cause a small delay of the
order of (0.01sec) at the start of executing each and every binary, therefore
think VERY carefully before adding anything to LD_LIBRARY_PATH or indeed using
software that will do so (such as SciSoft).

"
  exit ${exstat:-0}
}

verboseLog() {
  if [ ! -z "${vbose}" ]
  then
    echo "${execName}:: $1" > ${2:-/dev/stdout}
  fi
}

debugLog() {
  if [ ! -z "${debug}" ]
  then
    echo "${execName}::debug:: $1" > ${2:-/dev/stdout}
  fi
}

notQuietLog() {
  if [ -z "${quiet}" ]
  then
    echo "${execName}:: $1" > ${2:-/dev/stdout}
  fi
}

errorLog() {
  if [ ${quietLevel:-0} -lt 3 ]
  then
    echo "${execName}::Error:: $1" > ${2:-/dev/stderr}
  fi
}

warningLog() {
  if [ ${quietLevel:-0} -lt 2 ]
  then
    echo "${execName}::Warning:: $1" > ${2:-/dev/stderr}
  fi
}

execCmd() {
  if [ ! -z "${debug}" ] || [ ! -z ${dryRun} ]
  then
    echo "${execName}::execCmd:: $1"
  fi
  if [ -z "${dryRun}"  ]
  then
    eval ${1}
  fi
}

################################################################################
## Usage:
## checkVarIsSet <VAR-NAME> <level> [error-message] [exit-status]
##      <VAR-NAME>: name of variable to check for, no '$'
##         <level>: fatal|fatalNoExit|warn
## [error-message]: Optional Error/Warning message to print
##   [exit-status]: Optional exit status value
##
checkVarIsSet(){
  v1="$`echo $1`"
  v2="`eval echo $v1`"
  debugLog "Variable $1 is set to $v2"
  if [ -z "${v2}" ]
  then
    debugLog "Variable $1 is not set"
    case $2 in
      fatal)       errorLog   "${3:-Variable $1 not set}"; exstat=${4:-1} ; usage ;;
      fatalNoExit) errorLog   "${3:-Variable $1 not set}"; (( exstat=${exstat-0}+${4:-1} ));;
      warn)        warningLog "${3:-Variable $1 not set}";;
      *)           errorLog   "*** Coding error:: error-level not recognised"; exit 1
    esac
  else
    debugLog "Variable $1 is set to $v2"
  fi
}
################################################################################

################################################################################
## Definition of variable who need default values
execName="`basename ${0}`"
quietLevel=0

################################################################################
## Command line options
while [ ! -z "${1}" ]
do

  case $1 in
    -h|--help)    usage ; shift;;
    -D|--debug)   debug="-D"; quiet=""; vbose="-v";  quietLevel=0 ; shift;;
    -n|--dryRun)  dryRun="-n"; shift;;
    -q|--quiet)   quiet="${quiet} -q"; vbose=""; debug=""; (( quietLevel++ )) ; shift;;
    -v|--verbose) vbose="-v"; quiet="";  quietLevel=0 ; shift;;
    -a)           ABs="${ABs} ${2}"; shift; shift;;
    *)            exstat=1; usage; shift;;
  esac
done

################################################################################
## Main loop starts...

exstat=0

# Call other template.bash based scripts with command line options:
##  ${quiet} ${dryRun} ${debug} ${vbose}
# or
##  ${quiet} ${dryRun} ${debug:+-d} ${vbose}
# for older scripts with "-d" for debug rather than -D

sLLP="${LD_LIBRARY_PATH}"
verboseLog "Cleaning LD_LIBRARY_PATH = $LD_LIBRARY_PATH"
unset LD_LIBRARY_PATH
grep ^/ /etc/ld.so.conf > /tmp/$$.ld.so.conf
for D in `grep ^include[[:space:]] /etc/ld.so.conf | sed 's/include //'`
do
  debugLog "Adding $D to conf..."
  eval "grep -h ^/ /etc/$D >> /tmp/$$.ld.so.conf"
done
for D in `cat /tmp/$$.ld.so.conf`
do
  if [ -e $D ]
  then
    debugLog "Expanding $D"
    DD="`readlink -f $D`"
    if [ -z "`grep $DD /tmp/$$.ld.so.conf`" ]
    then
      echo $DD >> /tmp/$$.ld.so.conf
    fi
  fi
done
for P in `echo $sLLP | sed 's/:/ /g'`
do
  PP=`echo $P | sed 's|/$||'`
  canonicalPP=`readlink -f $P | sed 's|/$||'`
  verboseLog "Checking for $P == ${canonicalPP}"
  if [ -d ${P} ] \
     && [ -z "`grep ^[[:space:]]*${PP}[[:space:]]*$ /tmp/$$.ld.so.conf 2>/dev/null`" ] \
     && [ -z "`grep ^[[:space:]]*${PP}/[[:space:]]*$ /tmp/$$.ld.so.conf 2>/dev/null`" ] \
     && [ -z "`grep ^[[:space:]]*${canonicalPP}[[:space:]]*$ /tmp/$$.ld.so.conf 2>/dev/null`" ] \
     && [ -z "`grep ^[[:space:]]*${canonicalPP}/[[:space:]]*$ /tmp/$$.ld.so.conf 2>/dev/null`" ]
  then
    debugLog "Keeping $P"
    nLLP=${nLLP:+${nLLP}:}$P
  else
    debugLog "Stripping $P"
  fi
done
if [ -e /tmp/$$.ld.so.conf ]
then
  rm -f /tmp/$$.ld.so.conf
fi
if [ -z "${nLLP}" ]
then
  unset LD_LIBRARY_PATH
  echo "unset LD_LIBRARY_PATH"
else
  verboseLog "Setting LD_LIBRARY_PATH to ${nLLP}"
  echo "export LD_LIBRARY_PATH=${nLLP}"
fi

exit ${exstat:-0}
