ARCHIVE_DIR=archives
RESULTPRINTER="${PREFIX}/bin/rclmresultprinter.3d"
RESULTFILE=results

# Servers Settings
SERVER_AGENT_DB_FN="${PREFIX}/share/rcssserver3d/agentdb.xml"
#SPADES_CONF="--file /home/3d/tmp/configfiles/spades.conf"
#COMSERV1_CONF="--file /home/3d/tmp/configfiles/commserver.conf"
#COMSERV2_CONF="--file /home/3d/tmp/configfiles/commserver.conf"
SPADES_CONF=
COMSERV1_CONF=
COMSERV2_CONF=

SERVER=
COMSERV1=
COMSERV2=

# load user setting.
[ -f ${RCLM_USER_DIR}/3D ] &&  source ${RCLM_USER_DIR}/3D ]

## __before_match(team1, team2)
function __before_match {
    rm -rf Logfiles

    echo "Next match $1 vs $2"
    echo -n "Press [ENTER] to start."
    read

    return 0
}

## __run_match(team1, team2)
function __run_match {
    local TEAM1=$1
    local TEAM2=$2
    
    echo "$TEAM1 vs $TEAM2"
    
    cp subscript/rcssserver3D.rb.tmplate ${HOME}/.rcssserver3d/rcssserver3D.rb
    echo "spadesServer.queueAgents('${TEAM1}', 11)" >> ${HOME}/.rcssserver3d/rcssserver3D.rb
    echo "spadesServer.queueAgents('${TEAM2}', 11)" >> ${HOME}/.rcssserver3d/rcssserver3D.rb

    rcsoccersim3D | tee console.log

    _countdown 5 ': if you want to stop league, press Ctrl+C.'
    return 0
}
## __after_match(team1, team2)
function __after_match {
    local TEAM1=$1
    local TEAM2=$2

    NAME1=${TEAM1#*:}
    NAME2=${TEAM2#*:}
    DIR1=${TEAM1%:*}
    DIR2=${TEAM2%:*}

    GAMEDATE=`date +%Y%m%d%H%M`
    [ -d ${ARCHIVE_DIR} ] || mkdir ${ARCHIVE_DIR}
    local GAME=`${RESULTPRINTER} Logfiles/monitor.log`

    LOGNAME="${GAMEDATE}_${NAME1}_vs_${NAME2}"
    if [ -n "${GAME}" ]; then
	echo "$GAMEDATE $GAME" >> ${RESULTFILE}
    	set ${GAME}
	LOGNAME="${GAMEDATE}_$1_$3_vs_$2_$4"
    fi
    mv console.log Logfiles
    mv Logfiles "archives/${LOGNAME}"

    TIE=""
    if [ -z "${GAME}" ]; then
	echo -n "Tie game? [y/N]:"
    	read ans
	case $ans in
	[yY]*)
		TIE=y
		;;
	esac
    else
    	set ${GAME}
	echo 
    	[ "x$3" = "x$4" ] && TIE=y
    fi
    if [ "x$TIE" = 'xy' ]; then
	echo -n "Tie break, Run match again? [y/N]:"
    	read ans
	case $ans in
	[yY]*)
    		_countdown 15 ": wait extend match."
    		__run_match $TEAM1 $TEAM2
    		__after_match $TEAM1 $TEAM2
		;;
	esac
    fi
    return 0
}

## __wait_next_match
function __wait_next_match {
#    _countdown 15 ': wait next match.' 
	sleep 1
}
