#!/bin/bash

#
# `flowrotate.sh' By Mirko Steiner (mirko.steiner@slashdevslashnull.de)
#
# Shellscript for:
#	rotating flowfiles from:
# 		$NITPICKERDIR/current/
# 	to
#       	$NITPICKERDIR/YY-MM/DD
#
# 	and generate daily statistics in:
#		$NITPICKERDIR/YY-MM/DD.txt
#
# 	and collect the data for the month in:
#		$NITPICKERDIR/YY-MM/YY-MM.txt
#
#	where:	YY = current year without cent.
#		MM = current month
#		DD = current day
#	(Dont worry when the execution ends in the new day,
#	the date getting fetched at scriptstart)

# NOTES:
#
# Ensure that `aggr.pl' and `parse_flowfile' are in $NITPICKERDIR
# and run the script daily at 23:59 (should be a good value)
# 59 23 * * * /var/nitpicker/flowfilerotate.sh
# Don't forget to take a look at $OPTIONS!

NITPICKERDIR="/var/nitpicker"
NITPICKERBIN="/usr/local/sbin/nitpicker"
OPTIONS="-I eth0 -s "$NITPICKERDIR"/current"
YYMM=`date +%Y-%m`
DD=`date +%d`

# Killing nitpicker to get all date until now
killall nitpicker

# Test the existence of the directorys,
# else create them
if ! [ -d $NITPICKERDIR/$YYMM ]; then
	mkdir $NITPICKERDIR/$YYMM;
fi

if ! [ -d $NITPICKERDIR/$YYMM/$DD ]; then
	mkdir $NITPICKERDIR/$YYMM/$DD;
fi

# Move current flowfiles in the right directory
mv $NITPICKERDIR/current/* $NITPICKERDIR/$YYMM/$DD/

# Starting nitpicker again
$NITPICKERBIN $OPTIONS > /dev/null 2>&1 &

# Generating the stats
cd $NITPICKERDIR
./parse_flowfile $NITPICKERDIR/$YYMM/$DD 2> /dev/null > $NITPICKERDIR/$YYMM/$DD.parse
./aggr.pl $NITPICKERDIR/$YYMM/$DD.parse > $NITPICKERDIR/$YYMM/$DD.txt
./aggr.pl $NITPICKERDIR/$YYMM/*.parse > $NITPICKERDIR/$YYMM/$YYMM.txt

# sending mail
mail -s"Nitpicker Daily Status" admins@sinclan.org <<EOF
Daily Stats for $YYMM-$DD:
`cat $NITPICKERDIR/$YYMM/$DD.txt`
Summary for $YYMM:
`cat $NITPICKERDIR/$YYMM/$YYMM.txt`
EOF
