#!/bin/bash

if [ $# -lt 2 ]; then
    echo "Usage: mpi_ssh hostname command arg1 arg2 ..."
    exit 1
fi


doneParsing=false
while [ $doneParsing == "false" ];
do
    doneParsing=true

    if [ "$1" == "-x" ]; then
        shift
        hasx="-x"
        doneParsing="false"
    fi

    if [ "$1" == "-l" ]; then
        shift
        shift
        doneParsing="false"
    fi

    if [ "$1" == "-n" ]; then
        shift
        hasn="-n"
        doneParsing="false"
    fi
done


MPI_NODE=$1
shift


doneParsing=false
while [ $doneParsing == "false" ];
do
    doneParsing=true

    if [ "$1" == "-x" ]; then
        shift
        hasx="-x"
        doneParsing="false"
    fi

    if [ "$1" == "-l" ]; then
        shift
        shift
        doneParsing="false"
    fi

    if [ "$1" == "-n" ]; then
        shift
        hasn="-n"
        doneParsing="false"
    fi
done



EXECUTABLE=$1
shift



contact=${_CONDOR_SCRATCH_DIR}/contact
if [ ! -f ${contact} ]; then
	echo "error: contact file ${contact} can't be found"
	exit 1
fi



line=`grep "^[0-9]* ${MPI_NODE} " ${contact} | head -n 1`
if [ $? -ne 0 ]; then
	echo Host ${MPI_NODE} is not in contact file ${contact}
    cat ${contact}
	exit 1
fi


WORKING_DIR=`echo $line | awk '{print $4}'`


[ ${mpiDebug} == 1 ] && echo /usr/bin/ssh ${MPI_NODE} -oStrictHostKeyChecking=no -l `id -un` cd "${WORKING_DIR}" \; ${EXECUTABLE} "$@"
                             /usr/bin/ssh ${MPI_NODE} -oStrictHostKeyChecking=no -l `id -un` cd "${WORKING_DIR}" \; ${EXECUTABLE} "$@"

exit $?

