#!/bin/sh

umask 022

olddir=`pwd`

cd ~/serveur/

liste=`ls ~/clients/`
n=`echo $liste | wc -w`

echo "<TABLE ALIGN=\"CENTER\" BORDER=1 CELLPADDING=2 CELLSPACING=0>" > table.html
echo "  <TR ALIGN=\"CENTER\" BGCOLOR=\"#BBBBBB\">" >> table.html
echo "    <TD BGCOLOR=\"#777777\"><FONT COLOR=\"#FFFFFF\"><B>Att\\Def</B></FONT></TD>" >> table.html

a=1
while [ $a -le $n ]
do
  bot=`echo $liste | cut -f$a -d' '`
  eval score$bot=0
  echo "    <TD><B>$bot</B></TD>" >> table.html
  a=$[$a+1]
done

echo "  </TR>" >> table.html

rm -f ~/logs/*
echo "Début du tournoi : `date`" > matchs.txt

a=1
while [ $a -le $n ]
do
  b=1
  bot1=`echo $liste | cut -f$a -d' '`
  echo "  <TR ALIGN=\"CENTER\">" >> table.html
  echo "    <TD ALIGN=\"CENTER\" BGCOLOR=\"#BBBBBB\"><B>$bot1</B></TD>" >> table.html
  while [ $b -le $n ]
  do
    if [ $a -ne $b ]
    then
      bot2=`echo $liste | cut -f$b -d' '`
      echo -n "<a href=\"log.cgi?$bot1"_"$bot2&1\" target=\"_blank\" onclick=\"window.open('log.cgi?$bot1"_"$bot2&1','Pix','toolbar=no,location=no,directories=no,status=no,alwaysRaised=yes,dependant=no,menubar=no,scrollbars=yes,resizable=no,width=400,height=400'); return false\">$bot1 vs $bot2</a> : " >> matchs.txt
      result=`./combat.sh ~/clients/$bot1 ~/clients/$bot2 2> ~/logs/"$bot1"_"$bot2" | sed s/^0/-/ | sed s/^1/$bot1/ | sed s/^2/$bot2/`
      echo $result >> matchs.txt
      result2=`echo $result | cut -f1 -d' '`
      echo "    <TD><a href=\"log.cgi?$bot1"_"$bot2&1\" target=\"_blank\" onclick=\"window.open('log.cgi?$bot1"_"$bot2&1','Pix','toolbar=no,location=no,directories=no,status=no,alwaysRaised=yes,dependant=no,menubar=no,scrollbars=yes,resizable=no,width=400,height=400'); return false\">$result2</TD>" >> table.html
      vainqueur=`echo $result | cut -f2 -d':' | cut -f1 -d' '`
      if [ $vainqueur = '-' ]
      then
        eval score$bot1=\$[\$score$bot1+1]
        eval score$bot2=\$[\$score$bot2+1]
      else
        eval score$vainqueur=\$[\$score$vainqueur+3]
      fi
      killall $bot1 2> /dev/null
      killall $bot2 2> /dev/null
      killall serveur 2> /dev/null
    else
      echo "    <TD BGCOLOR=\"#777777\"></TD>" >> table.html
    fi
    b=$[$b+1]
  done
  echo "  </TR>" >> table.html
  a=$[$a+1]
done

echo "</TABLE>" >> table.html

echo "Fin du tournoi : `date`" >> matchs.txt

echo "Dernière mise à jour des résultats : `date`" > resultats.txt

bestscore=0
while [ $bestscore -ne -1 ]
do
  bestscore=-1
  a=1
  while [ $a -le $n ]
  do
    bot=`echo $liste | cut -f$a -d' '`
    eval botscore=\$score$bot
    if [ $botscore -gt $bestscore ]
    then
      bestscore=$botscore
      bestbot=$bot
    fi
    a=$[$a+1]
  done
  if [ $bestscore -ne -1 ]
  then
    echo "$bestbot : $bestscore" >> resultats.txt
  fi
  eval score$bestbot=-2
done

cd
tar -c logs | gzip > ~/www/logs.tar.gz 

cd $olddir