#!/bin/sh

# Appel seul, lance les stats AWStats du jour.
# Appel avec "all" lance les stats avec tous les fichiers .gz situs dans /var/log/apache
# Appel avec un nom de domaine en paramtre, rescanne tous les fichiers .gz pour ce domaine uniquement.


. /etc/alternc/local.sh

# This file specify a different ACCESSLOG when there is apachemerge in the server.
if [ -e /etc/alternc/webalizer.conf ]
then
    . /etc/alternc/webalizer.conf
fi

if [ -z "$1" ] 
    then
    if [ -z "$ACCESSLOG" ] 
	then
	ACCESSLOG="/var/log/apache/access.log.1"
    fi
else
    ACCESSLOG="/var/log/apache/access.log"
    MAXLOG=`ls -rt /var/log/apache/access.log.* | head -1 | sed -e 's/[^0-9]*\([0-9]*\).gz/\1/'`
fi

# Regenerate the awstat etc cache files : 
if [ -x ./awstats.cache.php ]
then
    ./awstats.cache.php
fi

if [ -z "$MYSQL_HOST" ] 
then
    MYSQL_HOST="localhost"
fi

CACHEDIR="/var/cache/awstats"
TMPLOG="/tmp/awstats.access.log"

mkdir -p $CACHEDIR
trap cleanup 1 2 15

function cleanup {
    rm -f $TMPLOG
}

function dostatgz {
    read DOM
    while [ "$DOM" ]
      do
      echo "processing $DOM (for $MAXLOG access files)"
       rm -f $TMPLOG
      for i in `seq $MAXLOG -1 2`
	do
        zgrep -h " $DOM$" $ACCESSLOG.$i.gz >>$TMPLOG 2>/dev/null
        echo -n "$i."
      done
      /usr/lib/cgi-bin/awstats.pl -config=$DOM
      read DOM
    done
}

function dostat {
    read DOM
    while [ "$DOM" ]
    do    
      echo "processing $DOM"
      grep -h " $DOM$" $ACCESSLOG >$TMPLOG 2>/dev/null
      /usr/lib/cgi-bin/awstats.pl -config=$DOM 
      read DOM
    done
}

if [ -z "$1" ]
    then
    mysql -h"$MYSQL_HOST" -p"$MYSQL_PASS" -u"$MYSQL_USER" "$MYSQL_DATABASE" -B -e "SELECT hostname FROM aws" |grep -v "^hostname" | dostat
else
    if [ "$1" = "all" ] 
	then
	mysql -h"$MYSQL_HOST" -p"$MYSQL_PASS" -u"$MYSQL_USER" "$MYSQL_DATABASE" -B -e "SELECT hostname FROM aws" |grep -v "^hostname" | dostatgz
    else
	echo "$1" | dostatgz
    fi
fi

cleanup
