#!/bin/bash

LOG_DIR="/var/log/apache2/vhosts/access_logs/"
VHOST_BASE="/var/www/"
STATS_OUT_DIR="/stats/"
BOOTSTRAP=1

for DIR in $(find /var/www/ -maxdepth 2 -name 'public_html' -type d); do
	VHOST=$(basename $(echo $DIR | sed "s/\/public_html.*//"))

	if [ "$BOOTSTRAP" == "1" ]; then
		[ ! -d $VHOST_BASE/$VHOST/goaccess-db ] && mkdir -p $VHOST_BASE/$VHOST/goaccess-db
		[ ! -d $VHOST_BASE/$VHOST/stats ] && mkdir -p $VHOST_BASE/$VHOST/stats
		[ $(grep -c "Alias /stats" /etc/apache2/sites-available/"$VHOST"_settings) -le 0 ] && sed -i "/Alias \/phpmyadmin.*/a \\\tAlias /stats \"\/var\/www\/$VHOST\/stats\/\"" /etc/apache2/sites-available/"$VHOST"_settings
		if [ ! -f /var/www/"$VHOST"/stats/.htaccess ]; then
			USER="$(stat -c "%U" "$VHOST_BASE/$VHOST/public_html" )"
			printf "AuthName \"restricted stuff\"\nAuthType Basic\nAuthUserFile /etc/apache2/users\n\nrequire user focus $USER" > $VHOST_BASE/$VHOST/stats/.htaccess
		fi
		for FILE in $(find $LOG_DIR -name $VHOST-access.log.*.gz); do
			zcat $FILE | goaccess \
			    --agent-list \
			    --anonymize-ip \
			    --persist \
			    --restore \
			    --config-file /etc/goaccess/goaccess.conf \
			    --db-path "$VHOST_BASE/$VHOST/goaccess-db" \
			    --log-format COMBINED \
			    --output "$VHOST_BASE/$VHOST/$STATS_OUT_DIR/index.html" \
			    -
		 done
	fi

	LOGFILES=()
	for ext in log log.1; do
	    logfile="$LOG_DIR/$VHOST-access.$ext"
	    [ -e "$logfile" ] && LOGFILES+=("$logfile")
	done

	if [ ${#LOGFILES[@]} -eq 0 ]; then
	    echo "No log files in '$LOGDIR'"
	    exit 0
	fi

	goaccess \
	    --agent-list \
	    --anonymize-ip \
	    --persist \
	    --restore \
	    --config-file /etc/goaccess/goaccess.conf \
	    --db-path "$VHOST_BASE/$VHOST/goaccess-db" \
	    --log-format "COMBINED" \
	    --output "$VHOST_BASE/$VHOST/$STATS_OUT_DIR/index.html" \
	    "${LOGFILES[@]}"
done