#!/bin/sh
# Copyright (c) 2008 Alon Swartz <alon@turnkeylinux.org> - all rights reserved

### BEGIN INIT INFO
# Provides:          confconsole
# Required-Start:    $all $local_fs
# Required-Stop:     $network $local_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Starts confconsole at boot time
# Description:       TurnKey GNU/Linux Configuration Console
### END INIT INFO

DESC="Configuration Console"
NAME=confconsole
DAEMON=/usr/bin/$NAME
PIDFILE=/var/run/$NAME.pid

set -e
. /lib/lsb/init-functions

# don't run the console if noconfconsole is passed as a boot param
for x in $(cat /proc/cmdline); do
    if [ $x = "noconfconsole" ]; then
        exit 0
    fi
done

# exit if openvt is not available
which openvt >/dev/null || exit 0

# Exit if the package is not installed
[ -x "$DAEMON" ] || exit 0

case "$1" in
  start)
    log_begin_msg "Starting $NAME"

    # turn off console blanking for install process
    setterm -blank 0

    # start the configuration console on a new virtual terminal
    START="start-stop-daemon --start \
               --pidfile $PIDFILE --make-pidfile \
               --startas $DAEMON"

    if $START --quiet --test; then
        chvt 1
        FGVT=$(fgconsole) openvt -c 8 -s -w -- $START &
    fi
    log_action_end_msg $?
    ;;

  stop)
    STOP="start-stop-daemon --stop --retry=TERM/30/KILL/5 --pidfile $PIDFILE"
    if $STOP --quiet; then
        rm -f $PIDFILE
    fi
    log_action_end_msg $?
    ;;

  restart|reload|force-reload)
    echo "Error: argument '$1' not supported" >&2
    exit 3
    ;;

  *)
    N=/etc/init.d/$NAME
    echo "Usage: $N {start|stop}" >&2
    exit 1
    ;;
esac

exit 0
