#!/bin/sh

# SGE Wrapper script to ensure correct environment variables are set

set -e

# For each of SGE_ROOT, SGE_CELL:
# 1) If the environment variable is set; use it
# 2) If not, look in /etc/default/gridengine
# 3) If still nothing, fall back to Debian defaults

DEFAULT_SGE_ROOT=/var/lib/gridengine
DEFAULT_SGE_CELL=default
CONFIG_PATH=/etc/default/gridengine
PROG=`basename $0`

# Save environment variables if we have been given them
# so we can restore them at the end
if [ ! -z "${SGE_ROOT}" ]; then
    _SAVED_SGE_ROOT="${SGE_ROOT}"
fi

if [ ! -z "${SGE_CELL}" ]; then
    _SAVED_SGE_CELL="${SGE_CELL}"
fi

# Read from our config file, this will set SGE_ROOT and/or SGE_CELL if
# appropriate

if [ -r "${CONFIG_PATH}" ]; then
    . "${CONFIG_PATH}"
fi

# If we still don't have anything set, fall back to the Debian defaults
if [ -z "${SGE_ROOT}" ]; then
    SGE_ROOT="${DEFAULT_SGE_ROOT}"
fi

if [ -z "${SGE_CELL}" ]; then
    SGE_CELL="${DEFAULT_SGE_CELL}"
fi

# If we had some environment variables, these should override
# anything else we were given so clobber it all again

if [ ! -z "${_SAVED_SGE_ROOT}" ]; then
    SGE_ROOT="${_SAVED_SGE_ROOT}"
fi

if [ ! -z "${_SAVED_SGE_CELL}" ]; then
    SGE_CELL="${_SAVED_SGE_CELL}"
fi

unset _SAVED_SGE_ROOT _SAVED_SGE_CELL

# Make sure we've exported the variables we need to
export SGE_ROOT SGE_CELL

exec /usr/lib/gridengine/${PROG} "$@"
