###########################################################################
#
# Shell verification. Try to be robust => very simple.
#
GAG_SHELL_TEST="shell test" || echo "source-gag.sh error: You must be under a sh-compatible shell!"
GAG_SHELL_TEST="shell test" || exit 1
unset GAG_SHELL_TEST
#
###########################################################################
#
# Main function definition
#
gagsou() {
    #
    # Variable and function definitions
    #
    GAGSOU_AUTHOR='J. Pety <pety@iram.fr>'
    GAGSOU_VERSION=`echo '$Revision$' | cut -d' ' -f2`
    GAGSOU_PROJECT='GILDAS  <http://www.iram.fr/IRAMFR/GILDAS>'
    GAGSOU_PROGNAME="gagsou"
    #
    gagsou_usage() {
	cat <<EOF 1>&2

Source the GILDAS environment of either the source tree (defined by
\$gagsrcdir) or the executable tree (defined by \$gagexedir). When the
\$gaghome enviroment variable exists, $GAGSOU_PROGNAME first defines the
\$gagsrcdir or the \$gagexedir using standard conventions (see build
script). Else $GAGSOU_PROGNAME assumes that \$gagsrcdir or \$gagexedir have
been defined elsewhere by the user. The default behavior (ie neither -e or
-s is set) is to source the executable tree as this facility is intended
first for users.

usage: $GAGSOU_PROGNAME [options] [version]

options:
  -h          Show this help page
  -v          Show version information
  -c compiler Replace default compiler by this one
  -o config   Add config to the config list
  -n config   Remove config from the default config list
  -u use-dir  Set gildas directory to use as a complement of local Gildas.
  -d version  On-the-fly selection of a default version. Useful in aliases.
  -e          Load executable tree environment
  -s          Load source     tree environment
  -m          Do not load environment (just define \$gagsrcdir and
		  \$gagexedir if needed)
  -l          List the available systems for the current version, and
              the available versions for the current \$GAG_EXEC_SYSTEM.

EOF
	gagsou_clean
    }
    #
    gagsou_showversion() {
	echo
	echo "$GAGSOU_PROGNAME version $GAGSOU_VERSION, by $GAGSOU_AUTHOR"
	echo "Project: $GAGSOU_PROJECT"
	echo
	gagsou_clean
    }
    #
    gagsou_message() {
	echo "$1"
    }
    #
    gagsou_error() {
	echo  1>&2
	echo "Error: $1" 1>&2
	echo  1>&2
	gagsou_clean
	return 1
    }
    #
    gagsou_exe_env_nohome() {
        if [ -d "$gagexedir/$GAG_EXEC_SYSTEM" ]; then
            if [ $dosource -eq 1 ]; then
                GAGRC=$gagexedir/etc/bash_profile
                if [ -e "$GAGRC" ]; then
                    source $GAGRC
                else
                    gagsou_error "Configuration file $GAGRC does not exist" || return $?
                fi
            fi
        else
            gagsou_error "No GILDAS version: $GAG_EXEC_SYSTEM in $gagexedir" || return $?
        fi
    }
    #
    gagsou_src_env_nohome() {
        if [ -d "$gagsrcdir" ]; then
            if [ $dosource -eq 1 ]; then
                source $gagadmdir/gildas-env.sh -c "$IN_COMPILER" $IN_CONFIG -u "$IN_USE" || return $?
            fi
        else
            gagsou_error "No GILDAS version in $gagsrcdir" || return $?
        fi
    }
    #
    gagsou_exe_env() {
        ogagexedir=$gagexedir
        if [ -h "$EXEDIR" ] && [ -e "$EXEDIR" ]; then
            gagexedir=`\dirname $EXEDIR`/`\readlink $EXEDIR`  # Translate e.g. gildas-exe-last symlink
        else
            gagexedir=$EXEDIR
        fi
        if [ -d "$gagexedir/$GAG_EXEC_SYSTEM" ]; then
            GAG_ROOT_DIR=$gagexedir
            if [ $dosource -eq 1 ]; then
                GAGRC=$gagexedir/etc/bash_profile
                if [ -e "$GAGRC" ]; then
                    source $GAGRC
                else
                    gagsou_error "Configuration file $GAGRC does not exist" || return $?
                fi
            fi
        else
            gagsou_error "No GILDAS version: $GAG_VERS ($GAG_EXEC_SYSTEM) in $gaghome" || return $?
        fi
    }
    #
    gagsou_src_env() {
        ogagsrcdir=$gagsrcdir
        if [ -h "$SRCDIR" ] && [ -e "$SRCDIR" ]; then
            gagsrcdir=`\dirname $SRCDIR`/`\readlink $SRCDIR`  # Translate e.g. gildas-src-last symlink
        else
            gagsrcdir=$SRCDIR
        fi
        if [ -d "$gagsrcdir" ]; then
            if [ $dosource -eq 1 ]; then
                source $gagadmdir/gildas-env.sh -c "$IN_COMPILER" $IN_CONFIG -u "$IN_USE" || return $?
            fi
        else
            gagsou_error "No GILDAS version: $GAG_VERS ($GAG_EXEC_SYSTEM) in $gaghome" || return $?
        fi
        export ogagsrcdir gagsrcdir
    }
    #
    gagsou_exe_list() {
        gagsou_system_list "$gaghome/gildas-exe-$GAG_VERS" || return $?
        gagsou_version_list "$gaghome/gildas-exe-*" "$GAG_EXEC_SYSTEM" || return $?
    }
    #
    gagsou_src_list() {
        gagsou_system_list "$gaghome/gildas-src-$GAG_VERS/integ" || return $?
        gagsou_version_list "$gaghome/gildas-src-*" "integ/$GAG_EXEC_SYSTEM" || return $?
    }
    #
    gagsou_system_list() {
        # $1: pattern for main directory
        found=0
        # List, ordered by time, newest first
        for x in `\ls -d $1/* 2> /dev/null`; do
            if [ ! -d "$x/bin" ]; then
              continue  # cycle loop
            fi
            if [ $found -eq 0 ]; then
                found=1
                gagsou_message "Available systems for $GAG_VERS version in $gaghome:"
            fi
            echo "    "`basename $x`
        done
        if [ $found -eq 0 ]; then
            gagsou_message "No available systems for $GAG_VERS in $gaghome"
        fi
    }
    #
    gagsou_version_list() {
        # $1: pattern for main directory
        # $2: subdirectory searched in matching directories
        found=0
        # List, ordered by time, newest first
        for x in `\ls -dt $1 2> /dev/null`; do
            if [ ! -d "$x/$2" ]; then
              continue  # cycle loop
            fi
            if [ $found -eq 0 ]; then
                found=1
                gagsou_message "Available versions for $GAG_EXEC_SYSTEM in $gaghome:"
            fi
            # Check if $x is a symlink to another version:
            y=`readlink $x`
            # Keep only the version name:
            x=`echo $x | perl -pe "s?$gaghome/gildas-\w+-(\w+).*?\1?"`
            # Feedback, with symlink translation if relevant
            if [ -z "$y" ]; then
                echo "    $x"
            else
                y=`echo $y | perl -pe "s?gildas-\w+-(\w+).*?\1?"`
                echo "    $x -> $y"
            fi
        done
        if [ $found -eq 0 ]; then
            gagsou_message "No GILDAS version for $GAG_EXEC_SYSTEM in $gaghome"
        fi
    }
    #
    gagsou_clean() {
	unset IN_COMPILER IN_CONFIG IN_USE IN_VERSION DEF_VERSION
	unset GAGSOU_AUTHOR GAGSOU_PROJECT GAGSOU_PROGNAME
	unset gagsou_usage gagsou_showversion gagsou_message gagsou_error
	unset gagsou_exe_env_nohome gagsou_src_env_nohome
	unset gagsou_exe_env        gagsou_src_env
	unset gagsou_exe_list       gagsou_src_list
	unset gagsou_system_list    gagsou_version_list
	unset dolist dosource executable
	unset gagsou_clean
    }
    #
    #######################################################################
    #
    # Option parsing
    #
    IN_COMPILER="default" # Default compiler will be setup by gagdefsys
    IN_CONFIG=            # Default config will be setup by gagdefsys
    IN_USE="default"      # Default use-dir is empty
    DEF_VERSION="default" # Default version will be setup by gagdefver
    dolist=0              # Default is not to list the versions
    dosource=1            # Default is to source environment
    executable=1          # Default is to select the executable tree.
    temp=`getopt "hveslmc:o:n:u:d:" "$@"`
    if [ $? -ne 0 ]; then gagsou_usage; return 2; fi
    eval set -- "$temp"
    unset temp
    while [ $1 != -- ]; do
	case $1 in
	-c) IN_COMPILER=$2; shift ;;
	-o) IN_CONFIG="$IN_CONFIG -o $2"; shift;;
	-n) IN_CONFIG="$IN_CONFIG -n $2"; shift;;
	-u) IN_USE=$2; shift ;;
	-d) DEF_VERSION=$2; shift ;;
	-e) executable=1 ;;
	-s) executable=0 ;;
	-m) dosource=0 ;;
	-l) dolist=1 ;;
	-v) gagsou_showversion; return 0 ;;
	-h) gagsou_usage; return 0 ;;
	esac
	shift # Next flag
    done
    shift # Skip double dash
    case $# in
	0) IN_VERSION=$DEF_VERSION ;;
	1) IN_VERSION=$1 ;;
	*) gagsou_usage; return 2 ;;
    esac
    set abc; shift # This line to avoid remanence effect in a portable way
    #
    #######################################################################
    #
    # Define gagadmdir
    #
    if [ -d "$gaghome/gildas-admin" ]; then
	gagadmdir=$gaghome/gildas-admin
    elif [ -d "$gagsrcdir/admin" ]; then
	gagadmdir=$gagsrcdir/admin
    else
	gagsou_error "Failed to define \$gagadmdir. Please define it by hand." || return $?
    fi
    export gagadmdir
    #
    # Define system in all cases
    #
    . $gagadmdir/define-system.sh                      # Load gagdefsys function
    if [ $executable -eq 1 ]; then
        gagdefsys -c $IN_COMPILER $IN_CONFIG || return $?  # Use it
    else
        gagdefsys -s -c $IN_COMPILER $IN_CONFIG || return $?  # Use it
    fi
    unset gagdefsys                                    # Remove gagdefsys function
    #
    # Define gagsrcdir, gagexedir and GAG_ROOT_DIR only when gaghome exists.
    # In all cases, try to source the environment.
    #
    if [ -z "$gaghome" ]; then
        #
        # No version definition: assume $gagsrcdir or $gagexedir are already set
	#
	# Setup environment or list
	#
	if [ $dolist -eq 1 ]; then
            gagsou_error "\$gaghome is unset: can not list versions" || return $?
	elif [ $executable -eq 1 ]; then
            gagsou_exe_env_nohome || return $?
	else
            gagsou_src_env_nohome || return $?
	fi
    else
	#
        # Setup environment or list
        #
        . $gagadmdir/define-version.sh  # Load gagdefver function
        gagdefver $IN_VERSION -n || return 1
        unset gagdefver
	if [ $dolist -eq 1 ]; then
            if [ $executable -eq 1 ]; then
                gagsou_exe_list || return 1
            else
                gagsou_src_list || return 1
            fi
	else
            if [ $executable -eq 1 ]; then
                gagsou_exe_env || return $?
            else
                gagsou_src_env || return $?
            fi
        fi
    fi
    #
    #######################################################################
    #
    # Cleaning
    #
    gagsou_clean
}
#
###########################################################################
#
gagsou $@
set abc; shift # This line to avoid remanence effect in a portable way
#
###########################################################################
