#!/bin/bash
#
# Bring up/down FCA manager daemon
#
# chkconfig: 2345 99 89
# description: Activates/Deactivates FCA manager daemon
#
### BEGIN INIT INFO
# Provides:       fca_managerd
# Required-Start:    $openibd
# Should-Start:      
# Required-Stop:     
# Should-Stop:       
# Required-Stop:
# Default-Start:     3 5
# Default-Stop:      0 1 2 6
# Short-Description: Mellanox Fabric Collective Accelerator
### END INIT INFO
fca_failure() {
  if [ "`type -t 'echo_failure' 2>/dev/null`" = 'function' ]; then
    echo_failure
  else
    echo $rc_failed
  fi
}

fca_success() {
  if [ "`type -t 'echo_success' 2>/dev/null`" = 'function' ]; then
    echo_success
  else
    echo $rc_done
  fi
}


fca_checkpid() {
    local i

    for i in $* ; do
        [ -d "/proc/$i" ] && return 0
    done
    return 1
}

fca_check_root() {
	if [ "`whoami`" != "root" ]; then
		echo Must be root to run this program
		exit 1
	fi
}



mydir=$(cd $(dirname $0); pwd)

if [ -x "$mydir/../bin/fca_manager" ]; then
	prefix=$(cd $mydir/../;pwd)
	FCA_MODE=tarball
	ulimit -c unlimited
else
    prefix=${prefix:="/opt/mellanox/fca"}
fi

echo Using FCA_HOME=$prefix

exec_prefix=$prefix/bin
lib_prefix="$prefix/lib64:$prefix/lib"

[ -f /etc/rc.d/init.d/functions ] && . /etc/rc.d/init.d/functions
[ -f /etc/rc.status ] && . /etc/rc.status

host=$(hostname)
prog=$exec_prefix/fca_manager
bin=${prog##*/}
runtime_log=${bin}-${host}-runtime.log

export LD_LIBRARY_PATH="${LD_LIBRARY_PATH}:${lib_prefix}"
#SUBSYS_FILE=/var/lock/subsys/$bin
CONFIG=/etc/sysconfig/$bin
PID_FILE=${prefix}/${bin}-${host}.pid

# Setting FCA Manager start parameters
if [ -f $CONFIG ]; then
    . $CONFIG
else
	OPTIONS="$prefix/etc/${bin}_spec.ini"
fi


DEBUG_OPT=${DEBUG_OPT:=""}
ACTION=$1

#########################################################################

version()
{
		$prog --version
}

start()
{
    local FCA_PID=

    pid=""

    if [ -f $PID_FILE ]; then
            local line p
            read line < $PID_FILE
            for p in $line ; do
                    [ -z "${p//[0-9]/}" -a -d "/proc/$p" ] && pid="$pid $p"
            done
    fi

    if [ -z "$pid" ]; then
        pid=`pidof -o $$ -o $PPID -o %PPID -x $bin`
    fi

    if [ -n "${pid:-}" ] ; then
        echo $"${bin} (pid $pid) is already running..."
    else

        # Start fca_manager
		echo -n "Starting FCA Manager"
		sh -c "ulimit -c unlimited && \
		       cd ${prefix} && \
		       ${DEBUG_OPT} $prog ${OPTIONS};
		       echo \$(date)': FCA manager exit'" \
		    &> ${prefix}/${runtime_log} &
		cnt=0
		alive=0
		while [ $cnt -lt 6 -a $alive -ne 1 ]; do
			echo -n ".";
			sleep 1
			alive=0
			FCA_PID=`pidof $prog`
			if [ "$FCA_PID" != "" ]; then
				alive=1
			fi
			let cnt++;
		done

        fca_checkpid $FCA_PID
        RC=$?
		if [ $RC -eq 0 ]; then
			fca_success 
			echo $FCA_PID > $PID_FILE
			if [ -w /var/run ]; then
				echo $FCA_PID > /var/run/${bin}.pid
			fi
			echo $FCA_PID > $PID_FILE
			#touch $SUBSYS_FILE
		else
			fca_failure
		fi
	echo

    fi
return $RC
}

stop()
{
    local pid=
    local pid1=
    local pid2=

    if [ -f $PID_FILE ]; then
            local line p
            read line < $PID_FILE
            for p in $line ; do
                    [ -z "${p//[0-9]/}" -a -d "/proc/$p" ] && pid1="$pid1 $p"
            done
    fi

    pid2=`pidof -o $$ -o $PPID -o %PPID -x $bin`

    pid=`echo "$pid1 $pid2" | sed -e 's/\ /\n/g' | sort -n | uniq | sed -e 's/\n/\ /g'`

    if [ -n "${pid:-}" ] ; then
        # Kill fca_manager
	echo -n "Stopping FCA Manager."
        kill -15 $pid > /dev/null 2>&1
		cnt=0; alive=1
        while [ $cnt -lt 2 -a $alive -ne 0 ]; do
		echo -n ".";
		alive=0
		for p in $pid; do
			if fca_checkpid $p ; then alive=1; echo -n "-"; fi
		done
		let cnt++;
		sleep $alive
	done

        for p in $pid
        do
            while fca_checkpid $p ; do
                kill -KILL $p > /dev/null 2>&1
                echo -n "+"
                sleep 1
            done
        done
        fca_checkpid $pid
        RC=$?
        [ $RC -eq 0 ] && echo_failure || fca_success
	echo
        RC=$((! $RC))
    else
	echo -n "Stopping FCA Manager."
        fca_failure
	echo
        RC=1
    fi

    # Remove pid file if any.
    rm -f $PID_FILE
	if [ -w /var/run ]; then
		rm -f /var/run/${bin}.pid
	fi
    #rm -f $SUBSYS_FILE
    return $RC
}

post_install() {
	$prefix/scripts/udev-update.sh ||:
}

post_uninstall() {
	[ -f %{udev_file_bak} ] && mv %{udev_file_bak} %{udev_file}
	chmod -f 0600 /dev/infiniband/umad* ||:
}

install_service() {
	fca_check_root
	if [ -n "${FCA_MODE}" ]; then
		echo Error: unsupported target for FCA tarball installations
		exit 1
	fi
	chkconfig --add fca_managerd
	chkconfig fca_managerd on
}

uninstall_service() {
	fca_check_root
	if [ -n "${FCA_MODE}" ]; then
		echo Error: unsupported target for FCA tarball installations
		exit 1
	fi
	stop >/dev/null 2>&1 ||:
	chkconfig --del fca_managerd ||:
}

status()
{
    local pid

    # First try "pidof"
    pid=`pidof -o $$ -o $PPID -o %PPID -x ${bin}`
    if [ -n "$pid" ]; then
            echo $"${bin} (pid $pid) is running..."
            return 0
    fi

     # Next try "/var/run/fca_manager.pid" files
     if [ -f $PID_FILE ] ; then
             read pid < $PID_FILE
             if [ -n "$pid" ]; then
                     echo $"${bin} dead but pid file $PID_FILE exists"
                     return 1
             fi
     fi
     echo $"${bin} is stopped"
     return 3
}



case $ACTION in
	start)
		start
		;;
	stop)
		stop
		;;
	restart)
		stop
		start
		;;
	status)
		status
		;;
	version)
		version
		;;
	install_service)
		install_service
		;;
	post_install)
		post_install
		;;
	post_uninstall)
		post_uninstall
		;;
	uninstall_service)
		uninstall_service
		;;
	condrestart)
		pid=`pidof -o $$ -o $PPID -o %PPID -x $bin`
		if [ -n "$pid" ]; then
			stop
			sleep 1
			start
		fi
		;;
	*)
		echo
		echo "Usage: `basename $0` {start|stop|restart|status}"
		echo
		exit 1
		;;
esac

RC=$?
exit $RC
