#! /bin/bash
#
# console-log   init script for console-log
#

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DESC="console-log"
LOGPAGER="/usr/lib/console-log/logpager"
LIBDIR="/var/lib/console-log"
CONFIGFILE="/etc/console-log.conf"

set -e

# WARNING! The pager is run as root. /usr/lib/console-log/logpager is a
# wrapper for less that configures less in a secure way to not allow shell
# escapes. If you have extended the pager wrappers to support other pagers,
# please submit your patches via the BTS.

do_start()
{
	cd $LIBDIR
	while read TTY FILE; do
	  case "$TTY" in
	    "" | "#" | \#* )
	      ;;
	    *)
	       if echo $TTY | grep "+\?[[:digit:]]\+" >/dev/null; then
	         if [ "${TTY:0:1}" == "+" ]; then
		   CHVT=1
		   TTY="${TTY:1}"
		 else
		   CHVT=0
		 fi
	         if [ -f $FILE ]; then
	           PAGER=$TTY-`echo $FILE | sed 's/\//_-_/g'`
	           ln -sf $LOGPAGER $PAGER
	           openvt -f -c $TTY -- run --restart --robust $LIBDIR/$PAGER +F $FILE
	           if [ -f /etc/console.noblank ]; then
	             setterm -blank 0 > /dev/tty$TTY
	           fi
		   [ $CHVT -eq 1 ] && chvt $TTY
                   echo -n "$FILE. "
	         else
	           echo "W: $FILE does not exist."
	         fi
	       else
	         echo "E: illegal tty $TTY."
		 exit 1
	       fi
	       ;;
	   esac
	done < $CONFIGFILE
}

do_something()
{
	ACTION="$1"
	cd $LIBDIR
	for PAGER in *; do
	  if [ "$PAGER" != "*" ]; then
            if isrunning -q $PAGER; then
  	      if [ $ACTION == "stop" ]; then
	        stop $PAGER >/dev/null 2>&1 || true # needed since stop never returns 0
	      elif [ $ACTION == "killrunning" ]; then
	        killrunning $PAGER
	      fi
	      TTY=${PAGER%%-*}
	      TERM=vt100 tput clear > /dev/tty$TTY
	    fi
	    if [ $ACTION == "stop" ]; then
	      rm -f $PAGER
	    fi
	  
	    # BUGS: This creates weird output if the log file name contains
	    # the string "_-_". Go figure.
	  
	    echo -n "${PAGER#*-}. " | sed 's/_-_/\//g'
	  fi
	done
}


case "$1" in
  start)
	echo -n "Starting $DESC: "
        do_start
	echo ""
	;;
  stop)
	echo -n "Stopping $DESC: "
  	do_something stop
	echo ""
	;;
  reload|force-reload)
	echo -n "Reloading $DESC: "
	do_something killrunning
	echo ""
        ;;
  restart)
	echo -n "Restarting $DESC: "
	do_something stop
	sleep 1
	do_start
	echo ""
	;;
  *)
	N=/etc/init.d/$NAME
	# echo "Usage: $N {start|stop|restart|reload|force-reload}" >&2
	echo "Usage: $N {start|stop|restart|force-reload}" >&2
	exit 1
	;;
esac

exit 0
