#!/bin/bash

echo '<<<mom>>>'
if [ -f /usr/sbin/pbs_mom ]
then
   if [ -f /usr/sbin/momctl ]
   then
      [ -d /var/spool/torque ] && TYPE="torque"
      [ -d /var/spool/pbs ] && TYPE="pbs"
      
      PID=0
      [ -f /var/spool/$TYPE/mom_priv/mom.lock ] && PID=$(cat /var/spool/$TYPE/mom_priv/mom.lock)
      
      if [ $PID -eq 0 ]; then
         echo "UNKNOWN mom not running, missing pidfile" 
         exit 0
      fi
      
      kill -0 $PID &>/dev/null
      if [ ! $? -eq 0 ]; then
         echo "UNKNOWN mom not running, PID $PID not running"
         exit 0      
      fi      
   
      cat /var/spool/$TYPE/mom_priv/config 2> /dev/null | awk '$1 == "$pbsserver" || $1 == "$clienthost"'
      /usr/sbin/momctl -d0 2> /tmp/mom_error_output | sed -n -e 's/job\[\(.*\)\].*state=\([A-Z]*\).*/job= \1 state= \2/p' -e 's/.*\(Version:.*\)PID.*/\1/p' -e 's/\(^Pending restart:.*\)/\1/p' | awk -v type=$TYPE '{if ($1 != "job=") print $0; else {"printjob /var/spool/" type "/mom_priv/jobs/" $2 ".JB | grep resc_req_total.nodect | cut -d= -f2" | getline numnodes; if (numnodes>1) print $0 " MULTINODE"; else print}}'
      if [[ -s /tmp/mom_error_output ]]; then
         echo -n "ERROR_OUTPUT: "
         cat /tmp/mom_error_output
      fi

      echo "mem $(free -k 2>/dev/null | grep '^Mem'| awk '{print $2}')"
      echo "swap $(free -k 2>/dev/null | grep '^Swap'| awk '{print $2}')"   

   else
      echo 'UNKNOWN momctl not installed'
   fi
   
else
   echo 'ERROR_OUTPUT: mom not installed'
fi
