#!/bin/bash
### BEGIN INIT INFO
# Provides:          configd
# Required-Start:    $local_fs $remote_fs $syslog
# Required-Stop:     $local_fs $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Configuration daemon
# Description:       Debian init script for the Configuration daemon
### END INIT INFO

source /lib/lsb/init-functions
declare progname=${0##*/}
declare action=$1; shift

source /etc/default/vyatta

HOME=/var/run/vyatta/configd
NAME=configd
DESC="configd"
PIDFILE=$HOME/configd.pid
RUNFILE=$HOME/running.config
DAEMON=/usr/sbin/configd
USER=configd
GROUP=vyattacfg
LOG=/var/log/vyatta/configd.log
SOCK=$HOME/main.sock

start ()
{
	log_action_begin_msg "Starting $DESC"
	mkdir -p $HOME
	mkdir -p "$(dirname $LOG)"

	# Start up
	/opt/vyatta/sbin/lu -user $USER \
		start-stop-daemon --start --quiet --pidfile $PIDFILE \
		--exec $DAEMON --name $NAME --background --  \
		-pidfile $PIDFILE -logfile $LOG -user $USER -group $GROUP -socketfile $SOCK \
		-runfile $RUNFILE

	if [[ $? == 1 ]]; then
		log_action_end_msg $?
		return
	fi

	i=0
	#Writing the pidfile signals that configd is ready to receive requests
	while [[ ! -f $PIDFILE ]]; do
		sleep 1
		((i++))

		#test for failures in log, only errors are printed to logfile
		logdata=$(<$LOG)
		if [[ $logdata != "" ]]; then
			echo
			echo "$logdata"
			log_action_end_msg 1
			return 1
		fi

		#timeout, this is an insane wait time, something is busted
		#average startup time is 300x faster than this
		if [[ $i -gt 10 ]]; then
			log_warning_msg "timeout waiting for configd"
			break
		fi
	done

	log_action_end_msg $?
}

stop()
{
	log_action_begin_msg "Stopping $DESC"
        start-stop-daemon --stop --quiet --pidfile=$PIDFILE \
		--name $NAME --oknodo --exec $DAEMON
	rm -f $PIDFILE
        log_action_end_msg $?
}

case "$action" in
    start) start ;;
    stop)  stop ;;
    force-reload | restart) stop; start ;;
    *)	log_failure_msg "usage: $progname [ start|stop|restart|force-reload ]" ;;
esac

exit $?
