#!/bin/bash

# Called with no parameters, launch the daily awstats stats
# called with "all", launch all stats with all apache log files from /var/log/alternc/sites/
# called with a domain name, launch the stats for this domain from all apache log files 

cd /usr/lib/alternc 
# AlternC system functions
. ./functions.sh

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

CACHEDIR="/var/cache/awstats" # Dans la sarge par defaut les données awstats sont stockées dans /var/lib/awstats ...
mkdir -p $CACHEDIR

function searchdomain {
    U_ID=$(mysql_query "SELECT uid FROM aws WHERE hostname='$1'" | grep -v "^uid")
    U_LOGIN=$(mysql_query "SELECT login FROM membres WHERE uid='$U_ID'" |grep -v "^login")
    DOM_DIR="$ALTERNC_LOGS/$U_ID-$U_LOGIN"
    if [ -d "$DOM_DIR" ] ; then
        echo $(find -P "$DOM_DIR" -mindepth 1 -maxdepth 2 -type f -iname "*.log*" -print0 | xargs -0)
    fi
}

function dostatgz {
    read DOM
    while [ "$DOM" ]
    do
      echo -n "processing $DOM"
      LOGAPACHE=$(searchdomain $DOM)
      if [ -n "$LOGAPACHE" ] ; then
        echo " (for access files in $LOGAPACHE )"
        /usr/lib/cgi-bin/awstats.pl -config=$DOM -update -LogFile="/usr/lib/alternc/logresolvemerge.pl $LOGAPACHE* |"
      else
        echo "\n No log found"
      fi
      read DOM
    done
}

function dostat {
    read DOM
    while [ "$DOM" ]
    do
      echo "processing $DOM"
      LOGAPACHE=$(searchdomain $DOM)
      if [ -n "$LOGAPACHE" ] ; then
        /usr/lib/cgi-bin/awstats.pl -config=$DOM  -LogFile="/usr/lib/alternc/logresolvemerge.pl $LOGAPACHE | "
      else
        echo "No log found"
      fi
      read DOM
    done
}

if [ -z "$1" ]
    then
    mysql_query "SELECT hostname FROM aws" |grep -v "^hostname" | dostat
else
    if [ "$1" = "all" ]
	then
	mysql_query "SELECT hostname FROM aws" |grep -v "^hostname" | dostatgz
    else
	echo "$1" | dostatgz
    fi
fi