#!/bin/bash
#------------------------------------------------------------------------------
# Script for running the C-code plate scanner, "evilscan", and the IDL-code
# plate correlator, "evilmap".
#
# D. Schlegel, 5 Sep 1999, Princeton
#------------------------------------------------------------------------------

# Test that the user is logged in as the user "mapper".
if ! `whoami | grep -q mapper` ; then
  echo "FAILED! You must be logged in as 'mapper', not as '"`whoami`"'."
  exit 1
fi

# Test both that the ssh daemon is running, and that ssh-add has been run
# to get password authentication for the user mapper.  If not, then we will
# fail when trying to copy files over to sdsshost.apo.nmsu.edu from the IDL
# proc EVILMAP.
key=`ssh-add -l`
if [ $? != 0 ] || [ -z "$key" ] ; then
  echo "FAILED! The 'sshd' daemon is not running.  You can start one"
  echo "by issuing the following two commands at the Unix prompt:"
  echo "  eval \`ssh-agent\`"
  echo "  ssh-add"
  echo "entering your passphrase after the second command. If \"map\""
  echo "still does not work, then call Craig Loomis or the observers."
  exit 1
fi
if ! `echo $key | grep -q mapper@apo.nmsu.edu` ; then
  echo "FAILED! Must run 'ssh-add' first.  You can do this now from the prompt."
  exit 1
fi

# Check that the system load is less than 0.1.  If not, then print a big
# warning message.
load=`uptime | awk '{print $(NF-2)+0.0}'`
bigload=`echo $load | awk '{if ($1 > 0.1) { print 1} else {print 0}}'`
if [ $bigload = 1 ] ; then 
  echo 
  echo "--------------------------------------------------------------"
  echo "!!!!!!!!!!!!!!!!!!!!!!!!!! WARNING !!!!!!!!!!!!!!!!!!!!!!!!!!!"
  echo "This computer is running other jobs with a load of "$load"."
  echo "These jobs are owned by:"
  top b n 1 | awk '{if ($NR > 9 && $10+0 > 5) {print "   USER="$2"  JOB="$13}}'
  echo "You should either quit the mapping program now (hit control-c),"
  echo "or map using the slow (s) mode, which takes 25 minutes."
  echo "--------------------------------------------------------------"
  echo
fi

# Query for the plugger's name(s) and the plate number
echo -n 'Enter your last name(s): '
read plugger
echo -n 'Enter plate number: '
read platenum anyExtras
echo -n 'Slow (s), fast (f), or extreme (e) mode? '
read mode anyExtras

# Run the plate scanner code
$IDLMAPPER_DIR/bin/evilscan 2> tmp.err << END
$plugger
$platenum
$mode
END

# Run the plate correlator code
if [ `awk '{if ($0 ~ "SCAN COMPLETE") {print $1}}' tmp.err` ]
then
  echo .com evilmap > tmp.map
  echo resolve_all >> tmp.map
  echo evilmap, $platenum, \
   copydir=\'sdsshost:/data/spectro/plugMapM\' >> tmp.map
  echo exit >> tmp.map
  idl tmp.map
  /bin/rm tmp.map
fi

echo "MAPPING COMPLETE"

/bin/rm tmp.err
#------------------------------------------------------------------------------
echo: No such file or directory
.com: No such file or directory
evilmap: No such file or directory
resolve_all
exit
