#!/bin/bash
#################################################################################
# /etc/cron.15min/autoshutdn RM20070202 
# 
# I run this script every 15 minutes on 192.168.1.4 (box) which is a server
# for printer/scanner shares, backups, and recording/viewing of dvb-t 
# programs. It checks to see if two work stations are up on the lan and then
# if there are any dvb recording (at) jobs pending. If rick and leila are 
# shutdown and there are no jobs in /var/spool/atjobs on box then "shutdown -h now"
# is run. Else the script will be run repeatedly as as a cron job as long as the 
# three conditions are not met.
#
# With Slackware, in order to run every 15 minutes you'll need to create a directory
# /etc/cron.15min, copy this script into /etc/cron.15min and then add the following
# lines to /var/spoolcron/crontabs/root:
#
#		 # Run 15 minute cron jobs 24 X 7:
#		 0,15,30,45 * * * * /etc/cron.15min/autoshtdn
#
# You could probably put the executable script anywhere as long as the path in the
# second line above points to the correct location.
#
#################################################################################
  
# Create some variables
IP1=192.168.1.2 # rick
IP2=192.168.1.3 # leila
QUDIR=/var/spool/atjobs # on box

# start a new log by redirecting with >
echo -e "Autoshtdn up, new log starts `date`" > /var/log/autoshutdn


# Test if Rick is up.
# Test1=1 if rick is down.
ping -c1 $IP1 > /dev/null 2>&1

if [ $? -eq 0 ];then
  TEST1=2
else
  TEST1=1
fi

# Test if Leila is up.
# Test2=1 if leila is down.
ping -c1 $IP2 > /dev/null 2>&1

if [ $? -eq 0 ] ; then
  TEST2=2
else
  TEST2=1
fi

# Test to see if there are any timeshifting jobs in /var/spool/atjobs.
# TEST3 will equal "1" if there are no jobs and "2" if there are.
if [ -e $QUDIR/* ] ; then
  TEST3=2
else
  TEST3=1
fi          

# Now if we have "1", "1", "1", we will shut down the server
if [ $TEST1 -eq 1 -a $TEST2 -eq 1 -a $TEST3 -eq 1 ] ; then
  echo -e "/nran autoshutdn script `date`" >> /var/log/autoshutdn
  echo -e "rick=$TEST1, leila=$TEST2, box=$TEST3, shutting down now.\n" >> /var/log/autoshutdn
  shutdown -h now
else
  echo -e "/nran autoshutdn script `date`" >> /var/log/autoshutdn
  echo -e "rick=$TEST1, leila=$TEST2, box=$TEST3, no shutdown now.\n" >> /var/log/autoshutdn
  # and the script will be run again in 15 minutes
fi

# End of script


