#!/bin/sh

# awstatsreporting.sh
# cronjob to update awstats pages for ISPMan virtual hosts
# Author: Wim Kerkhoff <wim@nyetwork.org>, July 28, 2004
# See: http://www.nyetwork.org/wiki/AWStats

# loosely based on awstats4vhost by Dave Capella
# http://grox.net/software/mine/awstats4vhost/index.php
# original copyright notice from install.awstats4vhost follows:
#
# *************
#
# install awstats www log statistics program for a virtual host
#
# dave@capella.ithaca.ny.us - Tue Mar  5 18:46:50 EST 2002
#
# copyright (c) 2002    dave w capella   All Rights Reserved
#
# May be freely distributed and used as long as this header is retained.
# All modifications must be clearly indicated.
#
# The author makes no promise of technical support. However, bug reports,
# suggestions, questions, and comments are welcome. All will be answered
# via electronic mail as time allows.
#
# NO WARRANTY OF ANY KIND EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
#
############################################################

ETCDIR=/etc/awstats
CFGHEADLESS=$ETCDIR/awstats.headless.conf
LOGDIR=/ispman/logs
CGI=/usr/lib/cgi-bin/awstats.pl
DOMAIN_ROOT=/ispman/domains
CACHE_ROOT=/ispman/awstats
CRONFILE=/etc/cron.hourly/awstats
LOGRESOLVE=/usr/share/doc/awstats/examples/logresolvemerge.pl

if [ "$UID" != "0" ] ; then
	 echo "must be run by root. I quit." 
	 exit 2 
fi

rm -rf $CRONFILE

for domain in $(ls $DOMAIN_ROOT/) ; do 
	if [ -d $DOMAIN_ROOT/$domain/vhosts ] ; then
		for pre in $(ls $DOMAIN_ROOT/$domain/vhosts) ; do 
			VHOST=$pre.$domain       

			LOGFILE="$LOGDIR/${VHOST}.access"
			CFGFILE=$ETCDIR/awstats.$VHOST.conf
			CACHEDIR="$CACHE_ROOT/$VHOST"

			if [ -r $LOGFILE ] ; then

				# make a cache directory.
				if [ ! -d "$CACHEDIR" ]; then 
					mkdir -p "$CACHEDIR"
				fi 

				# create config file
				#

				SLASHED=`echo ${VHOST} | sed -e 's/\./\\\./g'`
				
				touch $CFGFILE
				chmod 644 $CFGFILE

				# generate config contents
				# append a * to ${LOGFILE} to process all 
				# the rotated logs as well.
				cat <<EOF > ${CFGFILE}
# LogFile="$LOGFILE"
LogFile="$LOGRESOLVE ${LOGFILE} -dnslookup:4 |"
DirData="${CACHEDIR}"
HostAliases="${SLASHED} localhost 127\.0\.0\.1"
SiteDomain="${VHOST}"
EOF

				# add the rest of the template
				#
				cat $CFGHEADLESS >> $CFGFILE
				
				# update the stats...
				$CGI -config=$VHOST -update >> $CACHEDIR/update.log 2>&1
			else
				rm -rf $CFGFILE $CACHEDIR
			fi
		done
	fi
done
