#!/bin/bash
#
ticketfile=tickets.txt
numticket=`wc -w < $ticketfile`

# some bash versions have different RANDOM intervals
guess_randmax()
{
  sum=0
  for i in `seq 1 50`
  do
    sum=$[sum+RANDOM/50]
  done
  if [ ${#sum} -gt 7 ] ; then
    echo 2147483647
  else
    echo 32767
  fi
}

# random number function
rnd()
{
  bot=${1:-1}
  top=${2:-1}
  echo $[$RANDOM/($RANDMAX/($top-$bot+1))+$bot]
}

RANDMAX=`guess_randmax`
# now generate the actual random number
winidx=`rnd 1 $numticket`
numcols=5
echo "<html>"
echo "<head><title>lug-dd: Win or Lose</title></head>"
echo "<body>"
echo "<h1>Die Ziehung der Lottozahlen</h1>"
echo "<p>"
echo -n "<table border=1>"
col=0
# output ticket numbers
tr -s " " < $ticketfile | tr " " "\012" | \
(
while read t
do
  if [ $col -eq 0 ] ; then
    echo -ne "\n<tr>"
  fi
  col=$[(col+1)%numcols]
  echo -n "<td>$t "
done
# pad last row if necessary
while [ $col -ne 0 ]
do
  echo -n "<td>&nbsp; "
  col=$[(col+1)%numcols]
done
)
echo -e "\n</table>"
echo "<p>"
echo -n "<b>And the winner is: "
tr -s " " < $ticketfile | tr " " "\012" | sed -n "${winidx}p"
echo "</b>"
echo "</body>"
echo "</html>"

exit 0
