#! /bin/bash

# (c) 2007 Arne Rusek <zonk@matfyz.cz>
#
#    This is free software; you can redistribute it and/or modify it under the
#    terms of the GNU General Public License as published by the Free Software
#    Foundation; either version 2 of the License, or (at your option) any later
#    version.
#
#    It is distributed in the hope that it will be useful, but WITHOUT ANY
#    WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
#    FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
#    details.
#
#    You should have received a copy of the GNU General Public License along
#    with it; if not, write to the Free Software Foundation, Inc., 51 Franklin
#    St, Fifth Floor, Boston, MA  02110-1301  USA

# ALL CONFIG/LOG FILES MUST NOT HAVE SPACES IN FILENAME, who wants them anyway

SCRIPT=/usr/lib/cgi-bin/awstats.pl
MAIN_CONF=${AWSTATS_CONF:-/etc/awstats/awstats.conf}
MAIN_CONF_STR=${AWSTATS_CONF_STR:-awstats}
NICE=${AWSTATS_NICE:-10}
# ---

set -e

LOCKD="/tmp/awstats.$MAIN_CONF_STR.lock"
FAILFLAG=0
LOGFILE=/dev/zero

if ! mkdir $LOCKD; then
	echo "Previous run of awstats probably failed (lockdir $LOCKD found)." >&2
	echo "Please check awstats and then remove the directory." >&2
	exit 1
fi

function resolve_deps() {
	local log=""
	local incl=""
	local incls=""
	for i in `grep '^[[:space:]]*LogFile' $1 | tr ' ' '_'`; do
		log="`echo $i | sed -es'/.*=[_]*"\(.*[^\\]\)".*$/\1/'`"
		LOGFILE=$log
	done
	for i in `grep '^[[:space:]]*Include[[:space:]]*"' $1 | tr ' ' '_'`; do
		incl="`echo $i | sed -es'/.*Include[_]*"\(.*[^\\]\)".*$/\1/'`"
		if [ ! -r $incl ]; then
			echo "Required include $incl not readable!" >&2
			FAILFLAG=1
		fi
		incls="$incls $incl"
	done
	for i in $incls; do
		resolve_deps $i $(($2+1))
	done
	# only the last counts, doesn't it?
	if [ $2 -eq 0 -a ! -r $LOGFILE ]; then
		echo "Required log $LOGFILE not readable!" >&2
		FAILFLAG=1
	fi
	return $FAILFLAG
}

if [ -x $SCRIPT -a -f $MAIN_CONF ]; then
	if ! resolve_deps $MAIN_CONF 0; then
		rmdir $LOCKD
		echo "Error running awstats!" >&2
		exit 1
	fi
	nice -n $NICE $SCRIPT $MAIN_CONF -config=$MAIN_CONF_STR -update >/dev/null
	ec=$?
	rmdir $LOCKD
	exit $ec
fi
