#! /bin/bash

#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;; *) c=-h;; esac; y=${2#+}
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
  #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
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
    w=`ttys`
    if [ -z "$w" -o "$w" = "$y" ]; then
      shutdown $c now
      exit 0
    fi
    sleep 1; t=t+1
  done
} &
