#!/bin/bash


# Version 3.5
# Copyright Dectris Ltd.
# chkconfig: 2345 80 05
# description: grimsel
# The script will be executed at run levels 2,3,4,5 with start priority 80, stop priority 05

service=grimsel
runFile=/usr/local/dectris/bin/grimsel_dectris
pidFile=/var/run/grimsel_dectris.pid
statusFile=/var/run/grimsel_dectris.stat
pipe=/var/run/grimsel_dectris_files

function start() {
    if [ -e ${pidFile} ]; then
	echo "Error: $service is still running or has not been terminated properly"
	exit 1
    fi
    # Test for config file
    export CONFIG_FILE
    if [ -e /etc/grimsel_dectris.conf ]; then
	CONFIG_FILE=/etc/grimsel_dectris.conf
    elif [ -e /etc/grimsel_dectris/grimsel_dectris.conf ]; then
	CONFIG_FILE=/etc/grimsel_dectris/grimsel_dectris.conf
    fi
    # Read config file
    export LOG_FILE
    export _SOURCE_=$1
 
    if [ -z $CONFIG_FILE ]; then 
	echo "No configuration file found"
	exit 1
    else
	while read  key value rest; do
	    if [ ! -z "$key" ] && [ ! -z "$value" ]; then 
	        [ $key = "logfile" ] && LOG_FILE=$value
		[ $key = "source" ] && _SOURCE_=${_SOURCE_:=$value}
	    fi
	done < $CONFIG_FILE
    fi

    _SOURCE_=${_SOURCE_:='/'}
    _SOURCE_=/ramdisk/$_SOURCE_
    
    echo "Starting $service"
    nice -19 $runFile $*   
    sleep 1 # give grimsel time to create /var/run/grimsel_dectris_files
    /etc/init.d/furka restart
}


function stop() {
    echo "Stopping $service"
    if [ -e ${pidFile} ]; then
	for pid in $(tac ${pidFile}); do #tac: reverse order i.e. kill children first
	    if ps -p $pid > /dev/null; then
		pkill -9 -P $pid
		kill -9 $pid
	    fi
	    rm -f /tmp/file_list_$pid_*
	done
    else
	echo "No pid-file found"	
    fi  
    rm -rf $pidFile
    rm -rf $pipe
}

status() {

    export licenseFile
    export licenseValid
    while read key value
    do
      case $key in
	  "license_file")
	      licenseFile=$value
	      ;;
	  "license_valid")
              licenseValid=$value
	      ;;
      esac
    done < $statusFile

    echo -n $"Status of $service: "
    if [ -e ${pidFile} ]; then
	pid=$(head -n 1 $pidFile)
	if ps -p $pid > /dev/null; then
	    echo "$service is running with the PID $pid"
	else
	    echo "$service has no been terminated properly"
	fi
    else
	echo "$service is not running"	
    fi
    if [ "$licenseValid" = "yes" ]; then
	echo "License $licenseFile is valid"
    elif [  "$licenseValid" = "no" ]; then
	echo "License $licenseFile is not valid"
    fi
}



case "$1" in
  "start")
	shift 
        start $*
        ;;
  "stop")
        stop
        ;;
  "status")
        status
        ;;
  "restart")
        stop
	shift
        start $*
        ;;
  "--version")
	$runFile --version
	;;
   *)
   echo $"Usage: $service {start|stop|restart}"
   exit 1
esac
