#!/bin/bash
. /etc/sysconfig/openmamba-central

SOURCEDIR=/var/makedist
SNAPSHOT_MEDIADIR=/var/ftp/pub/openmamba/devel/media
MILESTONE1_MEDIADIR=/var/ftp/pub/openmamba/milestone1/media
CACHEDIR=/var/cache/openmamba-downloads
DESTBASEURL=/pub/openmamba/devel/media
SNAPDATE=`date +%Y%m%d`
GREPFILE=$CACHEDIR/current.dat


# do_all_langs_downloads()
#
# Parameters;
#
# $1: target
# $2: suffix
function do_all_langs_downloads() {
   local l f count count_curr
   
   tmpfile=`mktemp`
   
   echo "<script>" > $tmpfile
   for l in it en; do
      case $l in
         it) plus=$5 ;;
	 en) plus=$6 ;;
	 *) plus=0 ;;
      esac
      count=$plus
      for f in $CACHEDIR/*.dat; do
         count_curr=`grep -c "GET /pub/openmamba/$4/media/.*/openmamba-$1-$l-$2-.* 200 .*+$" $f`
	 count=`expr $count + $count_curr`
      done
      echo "downloadsArray['$1-$2-$l']='$count'" >> $tmpfile
   done
   echo "</script>" >> $tmpfile

   mv $tmpfile $3/$1/downloads.inc
   chmod 644 $3/$1/downloads.inc
}

for f in /var/log/httpd/www.openmamba.org-access_log.*.gz; do
   FILEDATE=`stat $f --printf=%Y`
   [ -e $CACHEDIR/$FILEDATE.dat ] || {
      echo "Creating new cache file from $f"
      gunzip -c $f | \
      grep "GET /pub/openmamba/.*/media/.*/openmamba-.* 200 .*+$" > $CACHEDIR/$FILEDATE.dat
   }
done

#[ ! -e $CACHEDIR -o \ 
#   $CACHEDIR /var/log/httpd/www.openmamba.org-access_log.1.gz
#[ -e $CACHEDIR/
# create a temp file with all successfull media downloads
grep "GET /pub/openmamba/.*/media/.*/openmamba-.* 200 .*+$" /var/log/httpd/www.openmamba.org-access_log > $GREPFILE

do_all_langs_downloads livecd milestone1 $MILESTONE1_MEDIADIR milestone1 0 0
#732 207
do_all_langs_downloads livecd snapshot $SNAPSHOT_MEDIADIR devel 0 0
# 732 207
do_all_langs_downloads livestudio milestone1 $MILESTONE1_MEDIADIR milestone1 0 0
# 97 10
do_all_langs_downloads livestudio snapshot $SNAPSHOT_MEDIADIR devel 0 0
# 69 49
do_all_langs_downloads livegames snapshot $SNAPSHOT_MEDIADIR devel 0 0
# 69 20
do_all_langs_downloads bootusb milestone1 $MILESTONE1_MEDIADIR milestone1 0 0
do_all_langs_downloads bootusb snapshot $SNAPSHOT_MEDIADIR devel 0 0
do_all_langs_downloads flash-1GB snapshot $SNAPSHOT_MEDIADIR devel 0 0
# 581 457
do_all_langs_downloads bootcd snapshot $SNAPSHOT_MEDIADIR devel 0 0
# 187 66
do_all_langs_downloads installdvd milestone1 $MILESTONE1_MEDIADIR milestone1 0 0

#rm -f $GREPFILE