#! /bin/sh
# $Id: get-next-slave,v 1.2 2003/11/22 03:00:14 ensc Exp $

# Copyright (C) 2003 Enrico Scholz <enrico.scholz@informatik.tu-chemnitz.de>
#  
# 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; version 2 of the License.
#  
# 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 for more details.
#  
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.


slave=$1
shift

unset DJINNI_VSERVERNAME
. /etc/sysconfig/fedora.us-build

lockfile="$SLAVE_LOCKDIR/.lock"
cnt=10

set -C
while true; do
    : >$lockfile || {
	test "$cnt" -ge 0 || {
	    echo "Failed to lock working area; aborting" >&3
	    exit 1
	}
	let --cnt
	sleep 1;
	continue;
    }
    break
done 3>&2 2>/dev/null 
trap "rm -f $lockfile" EXIT


if test -z "$slave"; then
    for i in `seq 0 $[ SLAVE_COUNT-1 ]`; do
	slave=$SLAVE_PREFIX$i
	test -e "$SLAVE_LOCKDIR/$slave" || break
	slave=
    done
fi

test "$slave" || {
    echo "Could not find a free slave; aborting" >&2
    exit 1
}

echo "$@" >"$SLAVE_LOCKDIR/$slave" || {
    echo "Failed to lock the slave; aborting" >&2
    exit 1
}

echo "$slave"
true
