#!/bin/sh

# chkconfig: 2345 30 70
# description: starts Open-MX driver

### BEGIN INIT INFO
# Provides:          mx
# Required-Start:    $network $syslog $remote_fs
# Required-Stop:     $network $syslog $remote_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Description:       Starts the Open-MX driver
### END INIT INFO


# Open-MX
# Copyright © inria 2007-2011 (see AUTHORS file)
#
# The development of this software has been funded by Myricom, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or (at
# your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# See the GNU General Public License in COPYING.GPL for more details.


# The following configuration variable may be defined in the OMX_CONFIG
# file or in the environment:
#  OMX_IFACES (which interfaces should be attached by the driver on load)
#  OMX_MODULE_PARAMS (module parameters to be passed to the driver)
#  OMX_MODULE_DEPENDS (other modules that should be loaded first, useful if modinfo is missing)
#  OMX_FMA_PARAMS (fma command-line parameters)
#  OMX_FMA_START_TIMEOUT (fma startup timeout)

# Note that this is replaced by make install, not configure!

scriptpath=`readlink -e $0`
scriptdir=`dirname $scriptpath`

OMX_PREFIX=/usr/open-mx
MAIN_DEVICE_NAME=open-mx
MAIN_DEVICE_GROUP=root
MAIN_DEVICE_MODE=0666
RAW_DEVICE_NAME=open-mx-raw
RAW_DEVICE_GROUP=root
RAW_DEVICE_MODE=0666
OMX_STATIC_MAPPING=0
OMX_PEER_DISCOVERY=omxoed
OMX_PEERS_FILE=/etc/open-mx/peers
FMS_RUN=/var/run/fms
FMS_SERVER=
OMX_RETRY=0
MODPROBE_PATH=/sbin/modprobe
MODINFO_PATH=/sbin/modinfo
INSMOD_PATH=/sbin/insmod
RMMOD_PATH=/sbin/rmmod

UDEV=1
UDEV_RULES_SRC=10-open-mx.rules
UDEV_RULES_DIR=/etc/udev/rules.d
UDEV_RULES_FILE=${UDEV_RULES_DIR}/${UDEV_RULES_SRC}

OMX_PID_FILE=/var/run/open-mx.peer-discovery.pid
OMX_CONFIG=/etc/open-mx/open-mx.conf
LINUX_RELEASE=$(uname -r)

set -e

if [ -f $scriptdir/${UDEV_RULES_SRC} ] ; then
    OMX_MODULE="$scriptdir/../driver/linux/open-mx.ko"
    TOOLS_DIR="$scriptdir/../tools"
else
    OMX_MODULE="${OMX_PREFIX}/modules/${LINUX_RELEASE}/open-mx.ko"
    TOOLS_DIR="${OMX_PREFIX}/bin"
fi

# save environment-enforced values
[ -n "$OMX_IFACES" ] && FORCE_IFACES="$OMX_IFACES"
[ -n "$OMX_MODULE_PARAMS" ] && FORCE_MODULE_PARAMS="$OMX_MODULE_PARAMS"
[ -n "$OMX_MODULE_DEPENDS" ] && FORCE_MODULE_DEPENDS="$OMX_MODULE_DEPENDS"
[ -n "$OMX_FMA_PARAMS" ] && FORCE_FMA_PARAMS="$OMX_FMA_PARAMS"
[ -n "$OMX_FMA_START_TIMEOUT" ] && FORCE_FMA_START_TIMEOUT="$OMX_FMA_START_TIMEOUT"

# read values from the config file
if test -r ${OMX_CONFIG}; then
    . ${OMX_CONFIG}
fi

# restore environment-enforced values
[ -n "$FORCE_IFACES" ] && OMX_IFACES="$FORCE_IFACES"
[ -n "$FORCE_MODULE_PARAMS" ] && OMX_MODULE_PARAMS="$FORCE_MODULE_PARAMS"
[ -n "$FORCE_MODULE_DEPENDS" ] && OMX_MODULE_DEPENDS="$FORCE_MODULE_DEPENDS"
[ -n "$FORCE_FMA_PARAMS" ] && OMX_FMA_PARAMS="$FORCE_FMA_PARAMS"
[ -n "$FORCE_FMA_START_TIMEOUT" ] && OMX_FMA_START_TIMEOUT="$FORCE_FMA_START_TIMEOUT"
# add defaults
[ -z "$OMX_FMA_START_TIMEOUT" ] && OMX_FMA_START_TIMEOUT=5
[ -z "$OMX_IFACES" ] && OMX_IFACES="all"

echoerr () {
    echo "$1" >&2
}

usage () {
	echo "Usage: $0 [options] <command> [module load params]"
	echo " Commands:	start stop status restart kill"
	echo "          	start-discovery stop-discovery restart-discovery kill-discovery"
	echo " Options:"
	echo "  --dynamic-peers		Force dynamic peer discovery"
	echo "  --dynamic-peers=<prog>	Force <prog> as the peer discovery tool instead of $OMX_PEER_DISCOVERY"
	echo "  --static-peers		Force static peers from $OMX_PEERS_FILE"
	echo "  --static-peers=<file>		Force static peers from <file>"
	echo "  --module=<file>		Use kernel module from <file>"
	echo "  --retry=<nb>			If a module is already loaded, sleep 10s and retry to load our module. Do this <nb> times"
	exit 1
}

cmd=
module_params=

while [ $# -ne 0 ] ; do
    if [ $1 = "--dynamic-peers" ] ; then
	OMX_STATIC_MAPPING=0
    elif [ ${1##--dynamic-peers=} != $1 ] ; then
	OMX_STATIC_MAPPING=0
	OMX_PEER_DISCOVERY=${1##--dynamic-peers=}
    elif [ $1 = "--static-peers" ] ; then
	OMX_STATIC_MAPPING=1
    elif [ ${1##--static-peers=} != $1 ] ; then
	OMX_STATIC_MAPPING=1
	OMX_PEERS_FILE=${1##--static-peers=}
    elif [ ${1##--module=} != $1 ] ; then
	OMX_MODULE=${1##--module=}
    elif [ ${1##--retry=} != $1 ] ; then
	OMX_RETRY=${1##--retry=}
    elif [ ${1##--} != $1 ] ; then
	usage
    elif [ -z "$cmd" ] ; then
	cmd=$1
    else
	module_params="$module_params $1"
    fi
    shift
done

[ -z "$cmd" ] && usage

OMX_MODULE_PARAMS="${OMX_MODULE_PARAMS} ifnames=${OMX_IFACES}"

# Remove the Open-MX module if loaded
unload_omx() {
    if grep -E 'open(-|_)mx' /proc/modules > /dev/null; then
        echo "Removing Open-MX driver"
        /sbin/rmmod open-mx
    fi

    # always remove device nodes, even if udev wasn't used.
    # we could be stopping a session from another build anyway
    rm -f "/dev/$MAIN_DEVICE_NAME" || true
    rm -f "/dev/$RAW_DEVICE_NAME" || true
}

# Check whether udev is running
udev_is_active() {
    test x$UDEV = x1 && ( test -d /run/udev || test -d /dev/.udev || test -e /dev/.udev.tdb || test -d /dev/.udevdb )
}

# Create device node file if necessary
check_or_create_device() {
    path="$1"; shift
    group="$1"; shift
    mode="$1"; shift
    kernelname="$1"; shift
    name="$1"; shift

    # create the device node if udev is disabled or if the file doesn't exist yet
    if ! udev_is_active || ! test -e "$path" ; then
	echo "  Creating '$path' which does not exist yet"
	major=$(sed -nr -e '/^Character devices:/,/^Block devices:/s/ *([0-9]+) *misc/\1/p' /proc/devices)
	minor=$(sed -nr -e 's/ *([0-9]+) *'$kernelname'$/\1/p' /proc/misc)
	if test -z "$major" -o -z "$minor"; then
	    echoerr "  [ERROR] Failed to retrieve $name device major/minor numbers"
	else
	    mknod "$path" c "$major" "$minor" \
		|| echoerr "  [ERROR] Failed to create $name device node"
	fi
	created_device=1
    fi

    # set device node mode and group if we created it manually, or if udev is disabled or doesn't know how to do it
    if test x$created_device = "x1" || ! udev_is_active || ! test -f "$UDEV_RULES_FILE" ; then
	echo "  Setting group '$group' and mode '$mode' on $name device '$path'"
	chgrp "$group" "$path" \
	    || echoerr "  [ERROR] Failed to set $name device mode"
	chmod "$mode" "$path" \
	    || echoerr "  [ERROR] Failed to set $name device group"
    fi

    # print the device status
    ls -l "$path" | sed -e 's/^/  /'
}

# Load the Open-MX module
load_omx() {
    params="$OMX_MODULE_PARAMS $module_params"
    echo "Loading Open-MX driver (with $params)"
    module=${OMX_MODULE}

    if test -f $module; then
	# modprobe the dependencies
	depends="$($MODINFO_PATH $module 2>/dev/null | grep ^depends | awk '{print $2}' | sed 's/,/ /') $OMX_MODULE_DEPENDS"
	for depend in $depends ; do
	    echo "Loading dependency module: $depend"
	    $MODPROBE_PATH $depend
	done

	# load the driver
	for i in $(seq 0 $OMX_RETRY) ; do
	    if ! $INSMOD_PATH $module $params ; then
		if [ $i != $OMX_RETRY ] ; then
		    echoerr "[ERROR] Failed to load the module. Sleeping (10s) then retrying"
		    sleep 10
		else
		    exit 1
		fi
	    else
		break
	    fi
	done
    else
	# module not found, the kernel probably changed since we installed Open-MX
	# try modprobe in case DKMS rebuilt the driver for the new kernel
	echoerr "[WARNING] Failed to find module $module, trying modprobe..."
	if $MODPROBE_PATH open-mx ; then
	    # looks good, let's hope DKMS compiled the module from the right source tree
	    # and with the right configure options
	    echoerr "[WARNING] Assuming modprobe loaded the right module"
	else
	    echoerr "[ERROR] Failed to modprobe open-mx"
	    exit -1
	fi
    fi

    # sleep a bit so that udev is done
    sleep 1

    # take care of device nodes
    echo "Creating device node files if necessary..."

    # say a bit about what's happening
    if ! udev_is_active ; then
	echo "  udev does not seem to be running,"
	echo "   creating device nodes manually."
    else if ! test -f "$UDEV_RULES_FILE" ; then
	echo "  udev rules not found (UDEV_RULES_FILE=$UDEV_RULES_FILE),"
	echo "   only creating device nodes manually and setting their"
 	echo "   group and mode if udev did not create them."
    else
	echo "  udev rules found (UDEV_RULES_FILE=$UDEV_RULES_FILE),"
	echo "   assuming udev manages device files, unless a file is missing."
    fi fi

    # do the actual work
    check_or_create_device "/dev/$MAIN_DEVICE_NAME" "$MAIN_DEVICE_GROUP" "$MAIN_DEVICE_MODE" "open-mx" "main"
    check_or_create_device "/dev/$RAW_DEVICE_NAME" "$RAW_DEVICE_GROUP" "$RAW_DEVICE_MODE" "open-mx-raw" "raw"
}

# Check the driver status
check_omx() {
    ${TOOLS_DIR}/omx_info -q
}

# Start the peer discovery
start_peer_discovery() {
    if test ${OMX_STATIC_MAPPING} -eq 1 ; then
	# initialize peers
	if test -r ${OMX_PEERS_FILE}; then
	    echo "Initializing peers using file '${OMX_PEERS_FILE}'"
	    ${TOOLS_DIR}/omx_init_peers -c "${OMX_PEERS_FILE}"
	else
	    echo "Peers file ${OMX_PEERS_FILE} does not exist, remember to run omx_peers_init with the correct file"
	fi
    else
	if [ "${OMX_PEER_DISCOVERY}" = "fma" ] ; then
	    discover_params="-d $OMX_FMA_PARAMS"

	    if [ -n "$FMS_SERVER" ] ; then
		discover_params="$discover_params -s $FMS_SERVER"
	    fi

	    if [ ! -d "$FMS_RUN" ] ; then
		echo "Creating FMS run directory $FMS_RUN..."
		mkdir -p "$FMS_RUN"
	    fi
	fi

	# save the old fma.pid to see if it changed
	[ "${OMX_PEER_DISCOVERY}" = "fma" ] && oldfmapid=$(cat "$FMS_RUN/fma.pid" 2>/dev/null || true)

	if [ ! -x ${TOOLS_DIR}/${OMX_PEER_DISCOVERY} ] || [ ! -f ${TOOLS_DIR}/${OMX_PEER_DISCOVERY} ] ;  then
	    echoerr "[ERROR] Cannot find dynamic peer discovery to start (${OMX_PEER_DISCOVERY})"
	    return
	fi

	echo "Starting the dynamic peer discovery (${OMX_PEER_DISCOVERY} ${discover_params})"
	${TOOLS_DIR}/${OMX_PEER_DISCOVERY} ${discover_params} >/dev/null 2>&1 &
	pid=$!

	# wait a bit for the process to start (and maybe fail)
	sleep 5

	if [ "${OMX_PEER_DISCOVERY}" = "fma" ] ; then
	    # FMA can take up to 10 seconds
	    echo "Waiting ${OMX_FMA_START_TIMEOUT}s for FMA to start..."
	    sleep $OMX_FMA_START_TIMEOUT
	    # fma -d will daemonize, so the $pid child is gone.
	    # look in fma.pid and use it if it changed
	    newfmapid=$(cat "$FMS_RUN/fma.pid" 2>/dev/null || true)
	    [ "$newfmapid" != "$oldfmapid" ] && [ -n "$newfmapid" ] && pid="$newfmapid"
	fi
	cmdname=$(ps -p $pid -o comm= 2>/dev/null || true)
	if [ -z "$cmdname" ] ; then
	    echoerr "[ERROR] Discovery exited early"
	else
	    echo "$pid $cmdname" > ${OMX_PID_FILE}
	    echo "Started as pid=$pid"
	fi
    fi
}

# Stop the peer discovery
stop_peer_discovery() {
    if [ -e ${OMX_PID_FILE} ] ; then
	cat ${OMX_PID_FILE} | while read pid cmdname ; do
	realcmdname=$(ps -p $pid -o comm= 2>/dev/null || true)
	if [ "$cmdname" != "$realcmdname" ] ; then
	    echoerr "[ERROR] Cannot find dynamic peer discovery to kill ($cmdname, pid=$pid)"
	else
	    echo "Killing the dynamic peer discovery ($cmdname, pid=$pid)"
	    kill -9 $pid || true
	    sleep 1
	fi
	done
	rm -f ${OMX_PID_FILE} || true
    else
	echoerr "[ERROR] Cannot find dynamic peer discovery to kill"
    fi
}

# Kill all possible peer discovery processes on the system
kill_peer_discovery() {
    echo "Killing all omxoed and fma processes"
    killall -v -9 omxoed || true
    killall -v -9 fma || true
    sleep 1
}

case "$cmd" in
    start)
	load_omx
	start_peer_discovery
	check_omx
	;;
    stop)
	stop_peer_discovery
	unload_omx
	;;
    kill)
	kill_peer_discovery
	stop_peer_discovery
	unload_omx
	;;
    restart)
	stop_peer_discovery
	unload_omx
	load_omx
	start_peer_discovery
	check_omx
        ;;
    start-discovery)
	start_peer_discovery
	;;
    stop-discovery)
	stop_peer_discovery
	;;
    kill-discovery)
	kill_peer_discovery
	stop_peer_discovery
	;;
    restart-discovery)
	stop_peer_discovery
	start_peer_discovery
	;;
    status)
	if grep -E 'open(-|_)mx' /proc/modules > /dev/null; then
	    echo "Open-MX driver is loaded"
	    cat "/dev/$MAIN_DEVICE_NAME"
	    check_omx
	else
	    echo "Open-MX driver is not loaded"
	fi
	;;
    *)
	echoerr "[ERROR] Unknown command: $cmd"
	usage
esac

exit 0
