#!/bin/sh

# Open-MX
# Copyright © inria 2007-2010 (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.


app=
opts=
sender_opts='-d localhost -e 3'
suspend=false


echoerr() { echo "$1" >&2	 ;}
error()	  { echoerr "ERROR => $1";}
fatal()	  { error "$1" && exit 1 ;}


print_usage()
{
    cat <<EOM

Usage : $0 [options] <test> [sender/receiver options] -- [sender options]

Options :
    -s | --suspend  Suspend the receiver just after having spawned it

EOM
}

detect_help_request()
{
    case $# in
	1)
	    case $1 in
		-h|--help) print_usage && exit 0 ;;
	    esac
    esac
}

parse_cli()
{
    while [ $# -gt 0 ] ; do
	case $1 in
	    -s|--suspend)   suspend=true ;;
	    *)		    break
	esac

	shift
    done

    if [ $1 ] ; then
	app=$1
	shift
    fi

    while [ $# -gt 0 ] ; do
	case $1 in
	    --)	sender_opts= ; shift; break ;;
	    *)  opts="$opts $1"
	esac

	shift
    done

    while [ $# -gt 0 ] ; do sender_opts="$sender_opts $1"; shift; done
}

bind_processes_on_multicore()
{
    __core=$(cat /proc/cpuinfo	\
           | grep processor	\
	   | tail -n 1		\
	   | sed -re 's/^processor\s*:\s*([0-9]+)\s*$/\1/')

    __core=$(expr $__core + 1)

    case $__core in
        1) ;;
        *) export OMX_PROCESS_BINDING=0,,,1
    esac

    unset __core
}

do_run()
{
    [ "$OMX_TEST_VERBOSE" = 2 ] && bind_processes_on_multicore

    $app $opts & __pid=$!

    # I think this is a bit dirty but I currently have not better...
    sleep 1
    { ps | grep -q $__pid; } || exit 1

    $suspend && kill -STOP $__pid
    sleep 1

    $app $opts $sender_opts
    __ret=$?

    kill -9    $__pid >/dev/null 2>&1
    kill -CONT $__pid >/dev/null 2>&1

    return $__ret
}



detect_help_request "$@"

parse_cli "$@"

[ $app ] || fatal "Missing test argument."

do_run
