#!/bin/bash

# Help from: http://www.administrator.de/index.php?content=43744
#            http://www.vdr-portal.de/board/thread.php?threadid=97411
#            http://www.vdr-portal.de/board17-developer/board20-c-c-scripten/p1204341-altes-problem-wieder-da-rechner-vdr-fileserver-automatisch-wieder-runterfahren-wenn-clients-offline-sind/#post1204341

# Purpose:  Started in /etc/rc.local
#           If user logs in, terminate
#           If ping to clients listet in auto-shutdown-ips.dat successfull stay active
#           If ping not successfull and no user logged in then shutdown

# IPs of the clients
CLIENTS=`cat /usr/local/bin/auto-shutdown-ips.dat`

loop_active=1
while [ $loop_active -eq 1 ]
do
   # 10 sec for testing, otherwise some minutes before next loop
   sleep 600                        # Give me 10 minutes before loggin in and between loops...
   keep_alive=0                     # Preset keep_alive FALSE

   #
   # Check if a user is logged in. If true, then exit script without doing a shutdown
   #
   if [[ -n $(users) ]]; then
      echo "$(users) logged in, exit script"
      keep_alive=1                  # Stay active since someone's logged in
      loop_active=0                 # Will terminate the while loop
      exit
   fi

   #
   # Check if a client is online. If true, then poll again later. If false exit script and shutdown
   #
   for i in $CLIENTS                # Loop thru the list of clients
   do
      ping -c 4 $i                  # Check if client is online
      if test $? -eq 0
      then
         keep_alive=1               # Stay active but keep executing the while loop...
         echo "$i can be pinged"
      fi
   done
   if test $keep_alive -eq 0        # If no user and no client is online exit while loop
   then
      loop_active=0                 # Will terminate the while loop and probably shutdown the system...
   fi
done

if test $keep_alive -ne 1
then 
   echo "Computer will shutdown now..."
   init 0                           # Shutdown command
   exit
fi

