#!/bin/bash

LC_ALL=en_US.UTF-8 # make sure numbers are properly formatted

statfile="statistics.php"

cat >$statfile <<'EOF'
<html>
<head>
<meta http-equiv="refresh" content="60; URL=http://fourier.math.uoc.gr/~mk/prog1718/scores/statistics.php">
<title>Στατιστικά προγραμμάτων για τη Γλώσσα Προγραμματισμού Ι (Φθιν. 2017-18)</title>
</head>
<body>
<pre>
EOF
formath="%-40s %10s %10s %10s %10s\n"
formatr="%-40s %10.2f %10d %10d %10d\n"

# Header row. Using gawk for correct UTF-8 spacing. Bash's printf is not UTF aware.
gawk "BEGIN {printf \"$formath\", \"Πρόβλημα\", \"Επιτυχία\", \"Υποβολές\", \"Σωστές\", \"Λάθος\"}" >> $statfile

for x in scores-*
do
    chmod ugo+r $x
    allquestions=`cat $x|wc -l`
    correct=`cat $x|grep OK|wc -l`
    percentage=`awk "BEGIN {printf \"%6.2f\", ${correct}/${allquestions}*100.}"`
    error=`cat $x|grep ERROR|wc -l`
    probname=`echo $x|sed 's/scores-//'|sed 's/.csv//'`
    printf "$formatr" \
        "$probname" "$percentage" "$allquestions" "$correct" "$error" >> $statfile
done

echo >> $statfile
export LC_ALL=el_GR.UTF-8 # for date formatting
echo -n "Τελευταία ενημέρωση " >> $statfile
date >> $statfile

cat >>$statfile <<'EOF1'
</pre>
</body>
</html>
EOF1

chmod ugo+r $statfile
