#!/bin/sh
# /etc/init.d/xfs: start or stop the X font server

set -e

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

test -x $DAEMON || exit 0

stillrunning () {
  if [ "$DAEMON" = "$(cat /proc/$DAEMONPID/cmdline 2> /dev/null)" ]; then
    true
  else
    false
  fi;
}

case "$1" in
  start)
    echo -n "Starting X-TT font server: xfs-xtt"
    start-stop-daemon --start --quiet --pid $PIDFILE --exec $DAEMON -- -user nobody || echo -n " already running"
    echo "."
  ;;

  restart)
    /etc/init.d/xfs-xtt stop
    if stillrunning; then
      exit 1
    fi
    /etc/init.d/xfs-xtt start
  ;;

  reload)
    echo -n "Reloading X-TT font server configuration..."
    if start-stop-daemon --stop --signal 10 --quiet --pid $PIDFILE --exec $DAEMON; then
      echo "done."
    else
      echo "xfs-xtt not running."
    fi
  ;;

  force-reload)
    /etc/init.d/xfs-xtt reload
  ;;

  stop)
    echo -n "Stopping X-TT font server: xfs-xtt"
    DAEMONPID=$(cat $PIDFILE | tr -d '[:blank:]')
    KILLCOUNT=1
    if [ ! -e $UPGRADEFILE ]; then
      start-stop-daemon --stop --quiet --pid $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 "not responding to TERM signal (pid $DAEMONPID)"
    else
      if [ -e $UPGRADEFILE ]; then
        rm $UPGRADEFILE
      fi
    fi
    echo "."
  ;;

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

exit 0
