#!/bin/sh
# Usage: slave <workdir> <envvar1> <value1> <envvar2> <value2> ... -- <command> <arg> ...
#
#  This wrapper is used to launch a process remotely with some environment variables
#  set.

# if there's any environment entries read them
if [ -f $HOME/.hudson_slave_profile ];
then
  . $HOME/.hudson_slave_profile
fi

# set the current directory
cd "$1"
shift

# fill in environment variables
while [ $# -gt 1 -a "$1" != "--" ];
do
  eval $1="$2"
  export $1
  shift 2
done

if [ "$1" != "--" ];
then
  echo Error: no command given
  exit -1
fi

shift

# execute. use eval so that variables can be expanded now
# this allows users to specify $HOME or $DISPLAY or anything else,
# and it works as expected.
#
# but since eval mess up with whitespace ('eval ls "a b"' means the same as 'eval ls a b')
# we need to re-escape arguments (we need to say 'eval ls \"a b\"' to achieve the desired effect)
list=""
for a in "$@"
do
  list="$list \"$a\""
done
eval "$list"
ret=$?
# these additional hooks seem to prevent "select: bad filer number" error
# on some systems, so use this as a precaution. We can afford to waste
# one second, can't we?
sleep 1
echo
exit $ret
