#!/bin/bash 
### BEGIN INIT INFO
# Provides:          kestrel
# Required-Start:    $local_fs $network $named $time $syslog
# Required-Stop:     $local_fs $network $named $time $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Description:       Script to run asp.net 5 application in background
### END INIT INFO

# Author: Ivan Derevianko aka druss <drussilla7@gmail.com>
# Modified by: Paul Schneider <redienhcs.luap@gmail.com>

. /lib/init/vars.sh
. /lib/lsb/init-functions

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
CONFIGS="/etc/kestrel/*.webenv"
DNX_USER_HOME=/srv/www/dnx
DNXRUNTIMEVERSION=$(cat /srv/www/dnx/alias/default.alias)

# fix issue with DNX exception in case of two env vars with the same name but different case
TMP_SAVE_runlevel_VAR=$runlevel
unset runlevel

running() {
  if [ -f $PIDFILE ]
  then
    DNXPID=$(cat $PIDFILE)
    if kill -0 $DNXPID 2>/dev/null
      then
	    return 0
    fi
  fi
  return 1
}


setdnxenv() {
    env=$1
    . $env
    # reset all except the name to default values
	export ASPNET_ENV=$NAME
	WWW_USER=www-data
	DNXRUNTIME=${DNX_USER_HOME}/runtimes/${DNXRUNTIMEVERSION}/bin/Microsoft.Dnx.Host.Mono.dll
	PROJECT=approot/Web
	CONFIGURATION=Release
	ROOT=/srv/www/yavsc
    DESC="$NAME"
    PIDFILE=/var/run/kestrel-${NAME}.pid
	export MONO_OPTIONS="--server"
    # reset to specified values
    . $env
}

status() {
  for env in $CONFIGS
  do
    setdnxenv "$env"
	if running;
	then
		echo "Service running $DESC (pid: $DNXPID)"
	else
		echo "Service stopped ($DESC)"
	fi
  done
}


start() {
  for env in $CONFIGS
  do
    setdnxenv "$env"
	if running; then
		echo "Service already running $DESC" "$NAME"
		log_end_msg 1  
	else
		log_daemon_msg "Starting service $DESC"
		start-stop-daemon -SbmCv -u $WWW_USER -p $PIDFILE -d $ROOT -x $DNXRUNTIME -- --project $PROJECT --configuration $CONFIGURATION $NAME >${ROOT}/kestrel-${NAME}.log
		log_daemon_msg "Service $DESC started"
		log_end_msg 0  
	fi
  done

}

stop() {
  for env in $CONFIGS
  do
    setdnxenv "$env"
	if ! running
	then
		echo Service not running $DESC
	    log_end_msg 1  
	else
		log_daemon_msg "Stopping service $DESC"
		start-stop-daemon -K -p "$PIDFILE"
		rm -f "$PIDFILE"
		log_daemon_msg "$DESC stopped."
		log_end_msg 0  
	fi
  done
}

case "$1" in
  start)
    start
    ;;
  stop)
    stop
    ;;
  restart)
    stop
    start
    ;;
  status)
    status
	;;
		
  *)
    echo "Usage: $0 {start|stop|restart}"
esac

export runlevel=$TMP_SAVE_runlevel_VAR


