#! /bin/sh

# $B%9%3%"$r%"%C%W%G!<%H$9$k%W%m%0%i%`(B 
# /* trr$B%[%9%H$G$J$1$l$P%[%9%H$K=hM}$7$F$b$i$&!#(B*/
# $B=q$-9~$_$N7A<0(B
# username score step total-times total-time date

# get parameters
trrdir=$1; trrhost=$2; trrscore=$3
user=$4; score=$5; step=$6; ttimes=$7; ttime=$8

# send to host
# if [ `hostname` != $trrhost ]; then
#  rsh $trrhost `echo $trrdir`update "$1 $2 $3 $4 $5 $6 $7 $8"
#  exit
# fi
# $B%M%C%H%o!<%/$NITD4$J$I$G%"%C%W%G!<%H$5$l$J$$$3$H$,(B
# $B$o$j$H5/$-$k$h$&$J$@(B

# set variables
date=`date '+%y.%m.%d, %H:%M'`
TMP=`echo $trrscore`.$$
TMP2=`echo $trrscore`2.$$
SFILE=`echo $trrscore`
lockfile=`echo $trrscore`.lock


# umask & trap
umask 000
trap "/bin/rm -f $TMP $TMP2 $lockfile; exit;" 0 1 2 15

# wait and lock
while [ -s $lockfile ]; do sleep 1; done
echo "`whoami` is locking" > $TMP2
mv $TMP2 $lockfile

# delete old record
sed -e '/^'$user'	/d' $SFILE > $TMP

# append new record
echo -n $user >> $TMP
if [ `echo -n $user | wc -c | awk '{print $1}'` -lt 8 ]; then
  echo -n "	" >> $TMP; fi
echo "	$score	$step	$ttimes	$ttime	$date" >> $TMP

# sort
sort -nr +1 -2 < $TMP > $TMP2

mv $TMP2 $trrscore

# unlock 
rm -f $lockfile $TMP $TMP2
