#!/bin/bash
set -e

BINDIR=$(dirname $0)

eval $($BINDIR/pegasus-config --sh-dump)

PEGASUS_GLITE_DIR=$PEGASUS_SHARE_DIR/htcondor/glite

if [ $# -gt 1 ] || [ "$1" == "-h" ] || [ "$1" == "--help" ]; then
    echo "Usage: $0 [-h] [GLITE_LOCATION]"
    exit 1
fi

if [ "$(uname -s)" == "Darwin" ]; then
    echo "WARNING: Condor doesn't normally ship with glite on OSX, so this is unlikely to work"
fi

if [ $# -eq 1 ]; then
    # User provided the glite dir
    GLITE_LOCATION=$1

    if [ ! -d "$GLITE_LOCATION" ]; then
        echo "GLITE_LOCATION does not exist: $GLITE_LOCATION"
        exit 1
    fi
else
    # We need to find the glite dir
    if ! which condor_config_val >/dev/null 2>&1; then
        echo "ERROR: Unable to find condor_config_val: Specify GLITE_LOCATION or add Condor to your PATH"
        exit 1
    fi

    # Make sure the directory exists
    GLITE_LOCATION=$(condor_config_val GLITE_LOCATION || true)
    if [ ! -d "$GLITE_LOCATION" ]; then
        echo "ERROR: GLITE_LOCATION from condor_config_val does not exist: $GLITE_LOCATION"
        echo "Condor might not be installed correctly, or you might be missing the condor-externals package."
        echo "If you are on Mac OS X, then your Condor probably doesn't have glite."
        exit 1
    fi
fi

# Do some sanity checks to make sure we have the right dir
GLITE_CONFIG=$GLITE_LOCATION/etc/batch_gahp.config
GLITE_BIN_DIR=$GLITE_LOCATION/bin

for f in "$GLITE_CONFIG" "$GLITE_BIN_DIR"; do
    if [ ! -e "$f" ]; then
        echo "ERROR: It looks like your GLITE_LOCATION is not correct"
        echo "This file seems to be missing: $f"
        echo "If Condor is not installed, then you will need to install it before proceeding."
        echo "If you have Condor installed, then you might be missing the condor-externals package."
        echo "If you are on Mac OS X, then your Condor probably doesn't have glite."
        echo "Please confirm your GLITE_LOCATION and try again"
        exit 1
    fi
done

# Copy all the pegasus scripts to the glite bin dir
for f in $PEGASUS_GLITE_DIR/*.sh; do
    echo "Installing $(basename $f)"
    cp $f $GLITE_BIN_DIR/
done

# Edit GLITE_CONFIG to add moab support
echo "Adding moab support to batch_gahp.config"
GLITE_CONFIG_BAK=$GLITE_CONFIG.$(date +%F)
cp $GLITE_CONFIG $GLITE_CONFIG_BAK
awk '
BEGIN {
    FS="=";
    has_binpath=0;
}
{
    if ($1 == "supported_lrms") {
        if (index($2,"moab")>0) {
            print($0);
        } else {
            print($0",moab");
        }
    } else {
        print($0);
    }
    if ($1 == "moab_binpath") {
        has_binpath=1;
    }
}
END {
    if (!has_binpath) {
        print("moab_binpath=`which msub 2>/dev/null|sed '\''s|/[^/]*$||'\''`")
    }
}
' $GLITE_CONFIG_BAK > $GLITE_CONFIG

