#!/bin/bash
# This is a wrapper around qtop, to be used in systems which go with OAR
#
# Fotis Georgatos, 03 November 2012, provided under MIT/GPL license

#
# NOTE: The code as it has currently is NOT reentrant - ie. run only one instance at a given time for any given user
#

OAR2PBSDIR=~/.local/oar2pbs	    # By convention this is a good temporary directory
mkdir -p $OAR2PBSDIR/tmp || exit 1  # If that fails, forget it alltogether

NODESTATES=$OAR2PBSDIR/tmp/nodestates.$$
CORESTATES=$OAR2PBSDIR/tmp/corestates.$$

PBSNODESTMP=$OAR2PBSDIR/tmp/pbsnodes_a.txt.$$
PBSNODES=$OAR2PBSDIR/pbsnodes_a.txt

QSTATTMP=$OAR2PBSDIR/tmp/qstat.txt.$$
QSTAT=$OAR2PBSDIR/qstat.txt

QSTAT_QTMP=$OAR2PBSDIR/tmp/qstat_q.txt.$$
QSTAT_Q=$OAR2PBSDIR/qstat_q.txt

# Capture the information about node states
oarnodes -s \
  | sed 's/^ /%/g;s/$/%/g'|xargs|sed 's/% %/,/g;s/% /\n/g;s/%//g' > $NODESTATES

# Capture the information about cores
oarnodes -Y \
  | grep -v '^  no'|grep -v '^  nex'|grep '^  [ajnc]'|grep -v '^  cpu[acft:]'|grep -v '^  c[lo]' \
  | sed 's/^  available_upto:.*/%/g'|sed  's/network_address: /network_address: = /g' \
  | sed "s/'//g;s/, .*//g"|cut -d: -f2-|xargs|sed 's/$/ /g'|tr % '\n'|sed 's/ \([0-9]*\) \([0-9]*\) = \(.*\) /\3 \1\/\2..fakelrms, /g' \
  | grep , > $CORESTATES

# Capture the information about jobs
oarstat |cut -c-11,26-|sed 's/^\(..........\) /\1 NNNNNNNNNNNNNN/g' \
  | cut -c-38,61-|sed 's/^\([0-9]*\) /\1            /g;s/ W / Q /g' \
  | sed 's/                      /                 Hi   /g' > $QSTATTMP # ensure at least some job name is available

# Produce the file with the information on queues
cat $QSTATTMP \
  | awk '{printf $5" "$4"\n"}'|sed '1,3d'|sort|uniq -c|sed 's/$/%/g' \
  | awk '{printf $2" "$3" "$1"\n"}' >$QSTATTMP.byqueue
(
for i in `cat $QSTATTMP.byqueue|cut -d' ' -f1|sort -u` ; do
  R=`grep $i" R%" $QSTATTMP.byqueue|cut -d' ' -f3`;R=${R:-"0"}
  Q=`grep $i" Q%" $QSTATTMP.byqueue|cut -d' ' -f3`;Q=${Q:-"0"}
  echo "$i             --      --       --      --  $R $Q --   E R"
done
echo "                                                 "$R $Q
) > $QSTAT_QTMP

# Produce the file with pbsnodes information
(
# the following oneliner is a hack to avoid the trouble with names like gaia-[0-9] , ie. one digit vs two or more
NODENAMES=`cut -d, -f1 $NODESTATES|sed 's/-\([0-9]\)$/-0\1/g'|sort|sed 's/-0\([0-9]\)$/-\1/g'`
for i in $NODENAMES; do
  SLOTSTATUS=`grep ^$i, $NODESTATES|tr ',' '\n'|grep :|cut -d: -f2|xargs|sed 's/Absent .standby./ Standby/g;s/Absent/Maintenance/g;s/Alive/free/g'`
  NP=`echo $SLOTSTATUS|wc -w`
  echo $i
  echo "     np = $NP"
  echo "     state = $SLOTSTATUS"
  echo -n "     jobs = "
  grep "^$i " $CORESTATES|cut -d' ' -f2-|xargs|sed 's/,$//g'
  echo
done  
) \
  | grep -v '^     jobs = $' \
  > $PBSNODESTMP

# Try to play as atomic operation
mv $PBSNODESTMP $PBSNODES
mv $QSTATTMP $QSTAT
mv $QSTAT_QTMP $QSTAT_Q

qtop -a -s $OAR2PBSDIR -c OFF $* |grep -v good.luck # reduce the number of lines in the output

