#!/bin/bash

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


service=furka
runFile=/usr/local/dectris/bin/furka_dectris
pidFile=/var/run/furka_dectris.pid
statusFile=/var/run/furka_dectris.stat

unalias -a 

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/furka_dectris.conf ]; then
	CONFIG_FILE=/etc/furka_dectris.conf
    elif [ -e /etc/furka_dectris/furka_dectris.conf ]; then
	CONFIG_FILE=/etc/furka_dectris/furka_dectris.conf
    fi
    # Read config file
    export LOG_FILE
    if [ -z $CONFIG_FILE ]; then 
	echo "No configuration file found"
	exit 1
    else
	while read line; do
	    line=$(echo $line | sed 's/#.*//' )
	    if [ "$(echo $line | grep -c logfile)" -gt 0 ]; then
		line=$(echo $line | sed 's/logfile \([^ ][^ ]*\)/\1/')
		if [ ! -z $line ]; then LOG_FILE=$line; break; fi
	    fi
	done < $CONFIG_FILE
    fi
    echo "Starting $service"
    $runFile $*    
}


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 -f $pidFile
}

function status() {

    export numberOfJobs
    export licenseFile
    export licenseValid
    while read key value
    do
      case $key in
	  "license_file")
	      licenseFile=$value
	      ;;
	  "license_valid")
              licenseValid=$value
	      ;;
	  "njobs") 
              numberOfJobs=$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"
	    echo "Number of copy jobs: $numberOfJobs"
	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 | restart | stop | status"
   exit 1
esac
