#!/bin/bash
#
# Sample script to generate a monthly SRG report. This script assumes that
# your logs are not already rotated. It handles log rotation before it 
# generates the report for the previous month
#
# A crontab line such as the one below should be used to trigger this script
# 1 0 1 * *       root    /usr/local/sbin/srg.monthly
#
# Keeps an unlimited number of monthly reports in the output directory!
# I hope you have lots of diskspace!!!
#
# NOTE: This script doesn't necessarily do what you want, it is provided 
# only as an example of what you may want to do at the end of the month.
# Please review it carefully before using it!
#
# Author:       Matt Brown <matt@mattb.net.nz>
# Version:      $Id: srg.monthly 243 2008-01-19 18:27:24Z matt $
#

# Path to SRG binary
SRG=/usr/bin/srg

# Utility to use for sending mail
MAIL_UTIL=/usr/bin/mail

# Top level directory for output reports
REPORTBASE=/var/www/srg_reports

# Configuration file location
CONFIGFILE=/etc/srg/srg.conf

# If you would like a summary report emailed to you each night, specify 
# your email address here
# eg. MAILUSER="srg-daily@yourdomain.com"
MAILUSER=""

# Log Files - Space separated list of logfiles to process
# eg. LOGS="access1.log access2.log access3.log"
ALOGS="/var/log/squid/access.log"
CLOGS="/var/log/squid/cache.log"

# Working file
TEMPFILE=/tmp/srg.monthly

# Permissions the Squid Logfiles should have
PERMS=640

# Check that the SRG binary exists and is executable
test -x $SRG || exit 0

# Make the logfile containing the last months data
rm -f $TEMPFILE
for log in $ALOGS; do
    cat $log >> $TEMPFILE
done

lastmon=$(date --date "1 day ago" +%Y%m)

# Stop squid
/etc/init.d/squid stop &> /dev/null

# Rotate access logs
for log in $ALOGS; do
    mv $log $log-$lastmon
    touch $log
    chown proxy: $log
    chmod $PERMS $log
done
# Rotate cache logs
for log in $CLOGS; do
    mv $log $log-$lastmon
    touch $log
    chown proxy: $log
    chmod $PERMS $log
done

# Start squid again
/etc/init.d/squid start &>/dev/null

# Gzip last months logs
for log in $ALOGS; do
    gzip $log-$lastmon
    chmod $PERMS $log-$lastmon.gz
done
for log in $CLOGS; do
    gzip $log-$lastmon
    chmod $PERMS $log-$lastmon.gz
done

# Get the date range
YEAR=$(date --date "last month" +%Y)
LASTMONTH=$(date --date "last month" +%m)
LASTDAY=$(date --date "1 day ago" +%d)
FIRSTDAY="$YEAR-$LASTMONTH-01"
LASTDAY="$YEAR-$LASTMONTH-$LASTDAY"

# Generate the srg reports
$SRG -C $CONFIGFILE -o $REPORTBASE/monthly -f $FIRSTDAY -t $LASTDAY:23:59:59 $TEMPFILE &>/dev/null

# Clean Up
rm -f $TEMPFILE
