#!/bin/sh
# /etc/init.d/kdm: start or stop the X display manager
# Script originally stolen from the xdm package
#
# description: K Desktop Manager
#
set -e

PATH=/bin:/usr/bin:/sbin:/usr/sbin
DAEMON=/usr/bin/kdm
PIDFILE=/var/run/kdm.pid
UPGRADEFILE=/var/run/kdm.upgrade

test -x $DAEMON || exit 0

# uncomment, if you want auto-logon to be runlevel-dependant
#test "$runlevel" || { runlevel=`runlevel`; runlevel=${runlevel#* }; }
#test "$runlevel" = 4 && ARG=-autolog || ARG=-noautolog

# uncomment, if you want tons of debug info in your syslog 
#ARG="$ARG -debug 1"

getpid () {
    if [ -f $PIDFILE ]; then
      DAEMONPID=$(cat $PIDFILE | tr -d '[:blank:]')
      true
    else
      false
    fi
}

stillrunning () {
  if [ "$(readlink /proc/$DAEMONPID/exe 2> /dev/null)" = "$DAEMON" ]; then
    true
  else
    # if the daemon does not remove its own pidfile, we will
    rm -f $PIDFILE $UPGRADEFILE
    false
  fi;
}

case "$1" in
  start)
    echo -n "Starting K display manager: "
    if getpid && stillrunning; then
      echo "already running."
    else
      start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON -- $ARG && echo "done."
    fi
  ;;

  restart)
    /etc/init.d/kdm stop
    if getpid && stillrunning; then
      exit 1
    fi
    /etc/init.d/kdm start
  ;;

  reload|force-reload)
    echo -n "Reloading K display manager configuration: "
    if start-stop-daemon --stop --signal 1 --quiet --pidfile $PIDFILE --exec $DAEMON; then
      echo "done."
    else
      echo "not running."
    fi
  ;;

  stop)
    echo -n "Stopping K display manager: "
    if ! getpid; then
      echo "not running (no $PIDFILE)."
      exit 0
    else
      KILLCOUNT=1
      if [ ! -e $UPGRADEFILE ]; then
        if ! start-stop-daemon --stop --quiet --pidfile $PIDFILE; then
	  echo "not running."
	  exit 0
	fi
      fi
      while [ $KILLCOUNT -le 5 ]; do
        if stillrunning; then
          kill $DAEMONPID
        else
          break
        fi
        sleep 1
        KILLCOUNT=$(expr $KILLCOUNT + 1)
      done
      if stillrunning; then
        echo "not responding to TERM signal (pid $DAEMONPID)."
      else
        rm -f $UPGRADEFILE
	echo "done."
      fi
    fi
  ;;

  *)
    echo "Usage: /etc/init.d/kdm {start|stop|restart|reload|force-reload}"
    exit 1
    ;;
esac

exit 0
