#!/bin/sh
. /etc/alternc/local.sh

if [ -e /etc/alternc/webalizer.conf ]
then
    . /etc/alternc/webalizer.conf
fi

if [ -z "$ACCESSLOG" ] 
then
    ACCESSLOG="/var/log/apache/access.log.1"
fi

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

CACHEDIR="/var/cache/alternc-webalizer"
DNSCACHE="/var/cache/alternc-webalizer/.dns.cache"
TMPLOG=`mktemp -p /tmp`
mkdir -p $CACHEDIR
trap cleanup 1 2 15

function cleanup {
    rm -f $TMPLOG
    rm -rf $CACHEDIR/*
}

function dostat {
    read LANG DOM DIR USER
    while [ "$DOM" ]
    do    
      if [ ! -d "$DIR" ]; then
	mkdir -p "$DIR"
	chown www-data:$USER "$DIR"
      fi
      export LC_ALL="$LANG"
      export LC_MESSAGES="$LANG"
      export LANG

      # first run: resolve IPs in cache
      grep -h " $DOM$" $ACCESSLOG | tee $TMPLOG | /usr/bin/webalizer -c $CACHEDIR/$DOM.conf -N 5 -D $DNSCACHE -
      # second run: process the stats
      /usr/bin/webalizer -c $CACHEDIR/$DOM.conf -N 0 -D $DNSCACHE $TMPLOG 2>/dev/null 
      read LANG DOM DIR USER
    done
}

# Clear the cache dir
rm -f $CACHEDIR/* 
# Fill the cache dir
/usr/lib/alternc/webalizer.cache.php

# Launch the stat
mysql -h"$MYSQL_HOST" -p"$MYSQL_PASS" -u"$MYSQL_USER" "$MYSQL_DATABASE" -B -e "SELECT lang,hostname,dir,uid FROM stats" |grep -v "^lang" | dostat

cleanup
