#! /bin/sh

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/sbin/brltty
NAME=brltty
DESC='Braille terminal driver'
PIDFILE=/var/run/$NAME.pid

test -f $DAEMON || exit 0

# /etc/brltty.conf may need to be propagated from the initramfs. (This is a
# pretty awful hack.)
if [ -e /dev/.initramfs/brltty.conf ] && [ -e /etc/default/brltty ]; then
	if [ -e /etc/brltty.conf ]; then
		mv /etc/brltty.conf /etc/brltty.conf.orig
	fi
	mv /dev/.initramfs/brltty.conf /etc/brltty.conf
	sed -i -e 's/^RUN_BRLTTY=.*/RUN_BRLTTY=yes/' /etc/default/brltty
fi

[ ! -f /etc/default/brltty ] || . /etc/default/brltty

# Edit /etc/default/brltty and set RUN_BRLTTY=yes to allow brltty to be
# started.
if [ "$RUN_BRLTTY" != yes ]; then
	exit 0
fi

set -e

case "$1" in
  start)
	echo -n "Starting $DESC: "
	start-stop-daemon --start --oknodo \
		--pidfile $PIDFILE --startas $DAEMON -- -P $PIDFILE
	echo "$NAME."
	;;
  stop)
	echo -n "Stopping $DESC: "
	start-stop-daemon --stop --quiet --oknodo --retry 5 --pidfile $PIDFILE
	echo "$NAME."
	;;
  restart|force-reload)
	echo -n "Restarting $DESC: "
	start-stop-daemon --stop --quiet --retry 5 --pidfile $PIDFILE
	start-stop-daemon --start --quiet \
		--pidfile $PIDFILE --startas $DAEMON -- -P $PIDFILE
	echo "$NAME."
	;;
  *)
	N=/etc/init.d/$NAME
	echo "Usage: $N {start|stop|restart|force-reload}" >&2
	exit 1
	;;
esac

exit 0
