#! /bin/bash

#space-separated list of all computers to shut down when the server shuts down
xts="ugly2"

#function for finding all open tty lines (text logins)
ttys() { who|awk '{print $2}'; }
#uncomment the following line, if you do not have a readlink executable
#readlink() { rlnk=`ls -l $1`; echo ${rlnk##* -> }; }

#get shutdown mode and controlling tty
case $1 in -r) c=-r;; -l) c=-l;; *) c=-h;; esac; y=${2#+}; i=$3; rh=$4
if test "$y" = "$2"; then
  #this voodoo is needed if running from "mc", etc.
  i=`whoami`; w=`ttys`; y=; n=$$
  while test "$n" != 1; do
    p=`readlink /proc/$n/fd/0`; pt=${p#/dev/}
    test "$p" != "$pt" -a "$w" != "${w##*$pt}" && { y=$pt; break; }
    n=`awk '/^PPid:/ {print $2}' /proc/$n/status`
  done
  #find requesting xterminal
  rh=${DISPLAY%:*}
  #exit kde session
  test $DISPLAY && dcop kdesktop default logout	& #"kwmcom logout" for kde1
  #gain privileges, if needed
  test $UID != 0 && exec sudo $0 $c +$y $i $rh
fi
{
  exec <>/dev/null >&0 2>&1
  #seconds to wait for x-session to shut down
  maxt=30
  declare -i t=0
  #wait for nobody being logged in
  while [ $t -lt $maxt ]; do
    if [ -z "`who|awk '/^'$i' +[^ @]*@'$rh' /'`" ]; then
      if [ "$rh" -a $c = -h -a -z "`who|awk '/^[^ ]+ +[^ @]*@'$rh' /'`" ]; then
	rsh $rh shutdown -h now & sleep 1
      fi
      if [ "$rh" ]; then
	hr=`date +%H`
	test $hr -ge 6 -a $hr -le 20 && exit 0
      fi
      while [ $t -lt $maxt ]; do
	w=`ttys`
	if [ -z "$w" -o "$w" = "$y" ]; then
	  test $c = -h && 
	    for h in $xts; do rsh $h shutdown -h now & done && sleep 1
	  shutdown $c now
	  exit 0
	fi
	sleep 1; t=t+1
      done
      exit 0
    fi
    sleep 1; t=t+1
  done
} &
