#!/bin/bash
#
# vhost-stack
# https://git.stack-source.com/msb/vhost-stack
# Copyright (c) 2022 Matthew Saunders Brown <matthewsaundersbrown@gmail.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)

# purge dns cache records older than 7 days
if [[ -f /var/lib/webalizer_dns_cache.db ]]; then
  /usr/bin/wcmgr -p7 /var/lib/webalizer_dns_cache.db
fi

# set virtualhosts array
virtualhosts=(`ls -1 /srv/www|grep -v ^html$`)

# only proceed if there are one or more virtualhosts
if [ ${#virtualhosts[@]} -gt 0 ]; then
  for virtualhost in "${virtualhosts[@]}"
  do
    if [[ -f /var/spool/apache2/$virtualhost.log ]]; then
      user=$(stat -c '%U' /srv/www/$virtualhost)
      if [[ ! -d /srv/www/$virtualhost/stats ]]; then
        install --owner=$user --group=$user --mode=755 --directory /srv/www/$virtualhost/stats
      fi
      /usr/bin/webazolver -Q -N 20 -D /var/lib/webalizer_dns_cache.db -o /srv/www/$virtualhost/stats /var/spool/apache2/$virtualhost.log
      /usr/bin/logger Running Webalizer for $virtualhost as user $user
      su --shell=/bin/bash -c "/usr/bin/webalizer -Q -D /var/lib/webalizer_dns_cache.db -N 0 -p -f -n $virtualhost -o /srv/www/$virtualhost/stats /var/spool/apache2/$virtualhost.log" $user
      /usr/bin/rm /var/spool/apache2/$virtualhost.log
    fi
  done
fi