#!/bin/sh
### BEGIN INIT INFO
# Provides:          codemeter
# Required-Start:    $network $local_fs $remote_fs
# Required-Stop:     $remote_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: CodeMeter Server
# Description:       CodeMeter Server
### END INIT INFO

# Author: WIBU-SYSTEMS AG

PATH=/sbin:/usr/sbin:/bin:/usr/bin
DESC="CodeMeter Server"
NAME=codemeter
DAEMON=/usr/sbin/CodeMeterLin
DAEMON_ARGS=""
USER=daemon
SCRIPTNAME=/etc/init.d/$NAME
CONFIGFILE=/etc/wibu/CodeMeter/Server.ini

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

# Load the VERBOSE setting and other rcS variables
. /lib/init/vars.sh

# Define LSB log_* functions.
# Depend on lsb-base (>= 3.0-6) to ensure that this file is present.
. /lib/lsb/init-functions

check_start () {
	if ! [ -r "$CONFIGFILE" ] ; then 
		# missing config file --> create an empty file for the daemon (requires root)
		touch "$CONFIGFILE"
		chown $USER "$CONFIGFILE"
	fi
	if [ "$(stat -c %U "$CONFIGFILE")" = "root" ] && [ "$USER" = "daemon" ] ; then
		# fix inaccessible config file
		chown $USER "$CONFIGFILE"
	fi
}

do_start()
{
	start-stop-daemon --start --quiet --chuid $USER --exec $DAEMON --test > /dev/null \
		|| return 1
	start-stop-daemon --start --quiet --chuid $USER --exec $DAEMON -- \
		$DAEMON_ARGS \
		|| return 2
	# if the config file is inaccessible to CodeMeter, the process will exit immediately --> make sure it's running:
	sleep .1
	pidof "$DAEMON" > /dev/null || return 2
}

do_stop()
{
	start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --exec $DAEMON
}

do_reload() {
	start-stop-daemon --stop --signal USR1 --quiet --exec $DAEMON
	return 0
}

case "$1" in
  start)
    check_start
    log_daemon_msg "Starting $DESC " "$NAME"
    do_start
    case "$?" in
		0|1) log_end_msg 0 ;;
		2) log_end_msg 1 ;;
	esac
  ;;
  stop)
	log_daemon_msg "Stopping $DESC" "$NAME"
	do_stop
	case "$?" in
		0|1) log_end_msg 0 ;;
		2) log_end_msg 1 ;;
	esac
	;;
  status)
       status_of_proc "$DAEMON" "$NAME" && exit 0 || exit $?
       ;;
  reload)
	log_daemon_msg "Reloading $DESC" "$NAME"
	do_reload
	log_end_msg $?
	;;
  restart|force-reload)
	log_daemon_msg "Restarting $DESC" "$NAME"
	do_stop
	case "$?" in
	  0|1)
		do_start
		case "$?" in
			0) log_end_msg 0 ;;
			1) log_end_msg 1 ;; # Old process is still running
			*) log_end_msg 1 ;; # Failed to start
		esac
		;;
	  *)
	  	# Failed to stop
		log_end_msg 1
		;;
	esac
	;;
  *)
	echo "Usage: $SCRIPTNAME {start|stop|status|reload|restart|force-reload}" >&2
	exit 3
	;;
esac

:
