#!/bin/sh
# /etc/init.d/xdm: start or stop the X display manager

set -e

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

test -x $DAEMON || exit 0

stillrunning () {
  if [ "$DAEMON" = "$(cat /proc/$DAEMONPID/cmdline 2> /dev/null)" ]; 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 X display manager: xdm"
    start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON || echo -n " already running"
    echo "."
  ;;

  restart)
    /etc/init.d/xdm stop
    if [ -f $PIDFILE ]; then
      if stillrunning; then
        exit 1
      fi
    fi
    /etc/init.d/xdm start
  ;;

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

  force-reload)
    /etc/init.d/xdm reload
  ;;

  stop)
    echo -n "Stopping X display manager: xdm"
    if [ ! -f $PIDFILE ]; then
      echo " not running (no $PIDFILE)."
      exit 0
    else
      DAEMONPID=$(cat $PIDFILE | tr -d '[:blank:]')
      KILLCOUNT=1
      if [ ! -e $UPGRADEFILE ]; then
        start-stop-daemon --stop --quiet --pidfile $PIDFILE --exec $DAEMON || echo -n " not running"
      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 -n " not responding to TERM signal (pid $DAEMONPID)"
      else
        if [ -e $UPGRADEFILE ]; then
          rm $UPGRADEFILE
        fi
      fi
    fi
    echo "."
  ;;

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

exit 0
