#!/bin/bash -f
#------------------------------------------------------------------------------
# Script to check the status of Son-of-Spectro.
# Hardwire the location of /data/spectro/spectrologs, whereas we should
# really get it from the cron table???
#
# D. Schlegel, Princeton, 11 Dec 2000
#------------------------------------------------------------------------------

#------------------------------------------------------------------------------
# If a second argument is give, such as "sos_status plate-mapper", or
# "sos_status observer@plate-mapper.apo.nmsu.edu", then run this command
# remotely on the machine "plate-mapper".

if [ $# = 1 ] ; then
  ssh $1 sos_status
  exit
fi

#------------------------------------------------------------------------------
# Test to see if the cron job is already loaded.

echo
vers=`crontab -l | awk 'BEGIN{begin = 0; end = 0}{if ($2 == "SOS" && $3 == "BEGIN") {begin = 1; vers = $4}; if ($2 == "SOS" && $3 == "END" && begin == 1) {end = 1}}END{if (begin == 1 && end == 1){print vers} else {print "0"}}'`
machine=`uname -n`
if [ $vers != "0" ] ; then
  echo "Son-of-Spectro cron IS running for USER="$USER" MACHINE="$machine"."
  echo "Loaded version="$vers"."
else
  echo "The Son-of-Spectro cron job is NOT running for USER="$USER" MACHINE="$machine"."
fi

#------------------------------------------------------------------------------
# Test to see if rsync is running

echo
rproc=`\ps -elf | grep aporsync | grep -v -e grep`
if [ -n "$rproc" ] ; then
  echo "The following aporsync jobs are currently running:"
  echo `\ps -elf | head -1`
  \ps -elf | grep aporsync | grep -v -e grep
  echo "You may need to kill old jobs if there is a problem."
else
  echo "No aporsync jobs are currently running."
fi

echo
rproc=`\ps -elf | grep startapo | grep -v -e grep`
if [ -n "$rproc" ] ; then
  echo "The following startapo jobs are currently running:"
  echo `\ps -elf | head -1`
  \ps -elf | grep startapo | grep -v -e grep
  echo "You may need to kill old jobs if there is a problem."
else
  echo "No startapo jobs are currently running."
fi


#------------------------------------------------------------------------------
# Make sure the spectrologs directory exists.
# Look for any lock files.

echo
logdir=$SPECTROLOG_DIR
if [ -z "$SPECTROLOG_DIR" ] ; then
   SPECTROLOG_DIR=/data/spectro/spectrologs
fi

if [ -e $logdir ] ; then
  files=`find $logdir -name "*.lock"`
  if [ -n "$files" ] ; then
    echo "The following lock files exist:"
    for i in $files ; do echo `ls -l $i` ; done
    echo "You may need to delete old lock files if there is a problem."
  else
    echo "No lock files exist."
  fi
else
  echo "The directory "$logdir" does not exist! That is very bad!!"
fi

#------------------------------------------------------------------------------
