#!/bin/sh

progname=$(basename "$0")
echo "----- starting $progname -----" >&2

if [[ ! -f $1 ]]; then
    echo "$progname: No GRAMI file" >&2
    exit 1
fi

#
# Try to extract condor_location from arc.conf.
#
[[ -r $ARC_CONFIG ]] || ARC_CONFIG=/etc/arc.conf

# This is for backwards compatibility (arc.conf used to be nordugrid.conf).
[[ -r $ARC_CONFIG ]] || ARC_CONFIG=$NORDUGRID_CONFIG
[[ -r $ARC_CONFIG ]] || ARC_CONFIG=/etc/nordugrid.conf

if [[ -r $ARC_CONFIG ]]; then
    eval "$(egrep '^[[:blank:]]*condor_(config|location)=' "$ARC_CONFIG")"
    condor_rm=$condor_location/bin/condor_rm
    if [[ -x $condor_rm ]]; then
        echo "$progname: found $condor_rm using $ARC_CONFIG"
        echo "$progname: found $condor_config using $ARC_CONFIG"
    fi >&2
fi

#
# Search PATH for condor_rm.
#
if [[ ! -x $condor_rm ]]; then
    IFS=:
    condor_rm=
    for i in $PATH; do
        if [[ -x "$i"/condor_rm ]]; then
            condor_rm=$i/condor_rm
            echo "$progname: found $condor_rm using PATH" >&2
        fi
    done
    unset IFS
fi

#
# If the file /etc/sysconfig/condor exists, see if it defines the variable
# CONDOR_LOCATION and look for condor_rm in $CONDOR_LOCATION/bin.
#
if [[ ! -x $condor_rm ]]; then
    if [[ -f /etc/sysconfig/condor ]]; then
        . /etc/sysconfig/condor
        condor_rm=$CONDOR_LOCATION/bin/condor_rm
    fi
    if [[ -x $condor_rm ]]; then
        echo "$progname:" \
             "found $condor_rm from /etc/sysconfig/condor" >&2
    fi
fi

#
# If all else fails, use the optional SUID root program condor_master_location
# to search /proc/<pid>/exe for links to the condor_master program, and use its
# directory to find condor_rm.
#
if [[ ! -x $condor_rm ]]; then
    progdir=$(cd "$(dirname "$0")"; pwd)
    if [[ -x $progdir/condor_master_location ]]; then
        condor_bindir=$(cd "$("$progdir"/condor_master_location)"/../bin; pwd)
        condor_rm=$condor_bindir/condor_rm
    fi

    if [[ -x $condor_rm ]]; then
        echo "$progname:" \
             "found condor_rm from condor_master_location ($condor_rm)" >&2
    fi
fi

if [[ ! -x $condor_rm ]]; then
    echo "$progname: could not find condor_rm!" >&2
    exit 1
fi

if [[ ! -r $condor_config ]]; then
    condor_config=$(dirname "$condor_rm")/../etc/condor_config
    [[ -r $condor_config ]] && echo "$progname:" \
        "$condor_config found above $condor_rm" >&2
fi

if [[ ! -r $condor_config ]]; then
    condor_config=$CONDOR_CONFIG
    [[ -r $condor_config ]] && echo "$progname:" \
        "$condor_config found using CONDOR_CONFIG environment variable" >&2
fi

if [[ ! -r $condor_config ]]; then
    echo "$progname: could not find Condor configuration file!" >&2
    exit 1
fi

eval "$(grep '^joboption_jobid=' "$1")"
echo "$progname: canceling job $joboption_jobid with condor_rm..." >&2
export CONDOR_CONFIG=$condor_config
$condor_rm ${joboption_jobid%.condor} >&2
echo "----- exiting cancel-condor-job -----" >&2
exit 0
