#!/bin/sh

# List nodes used by a running SGE job.

# Dave Love <fx@gnu.org>, 2009-01
# Copyright (C) 2009 The University of Liverpool
# Licence: FreeBSD <http://www.gnu.org/licenses/license-list.html#FreeBSD>

usage () {
    echo "Usage: $(basename $0) [-w] <jobid>
List nodes currently running SGE job number <jobid>.
-w means separate node names with commas, to produce a list suitable
for the -w arg of pdsh."
}

if [ $# -eq 0 -o $# -gt 2 ]; then
    usage 1>&2; exit 1
fi

sep='"\n"'

while [ $# -gt 0 ]; do
    case $1 in
	--help) usage; exit;;
	-w) sep='","';;
	-*) usage 1>&2; exit 1;;
	*) jobid=$1;;
    esac
    shift
done

if [ -z "$jobid" ]; then
    usage 1>&2; exit 1
fi

# The qhost output comprises a header and node lines up until the
# first node with a job in it, when the node ine is followed by
# another header and the job details.  Filter the headers and look for
# node lines, which have leading node names (no spaces).  If the
# following line has leading blanks and a number (job info), the node
# is busy.
qhost -j |
  awk '
/^HOSTNAME|^-/ {node=""}	# header

/^[[:blank:]]+(job-ID|-)/ {next}# header

/^[^[:blank:]]/ {node = $1}	# node

/^[[:blank:]]+[0-9]/ {		        # job
    if (node && ($1 == "'$jobid'")) {   # shell substitution!
	printf ("%s%s", sep, node)	# from previous line
       'sep=$sep'			# shell substitution!
    }
}'
[ $sep = '"\n"' ] && echo
