#!/bin/sh

# rolling disk usage reporting
# uses durep to save disk usage reports
# designed to be run each day from /etc/cron.daily
# so that you can look back over the past week to try and isolate where
# changes in disk space are happening
# also takes a snapshot once a month for longer term changes
# so you can look back up to one year

# to get a copy of durep, try googling for "durep"
# or use the durep package in debian

# tested and used on GNU Linux using bash
# GNU cp option --target-directory used, might not work on non-GNU systems

# $Id: durep-rolling,v 1.7 2002-12-15 12:53:37+11 matthewa Exp matthewa $

# this cron script by Matthew Arnison <maffew@cat.org.au>
# ideas pilfered from a backup script by Daniel O'Callaghan <danny@freebsd.org>

# to use: edit /etc/default/durep-rolling and add some filesystems
# to be reported on each night

# config

LANG=C
export LANG

test -f /etc/default/durep-rolling || exit 0

. /etc/default/durep-rolling

test -x $DUREP || exit 0
test -n "$FILESYSTEMS" || exit 0

# action

DOW=`date +%a`		# Day of the week e.g. Mon
DOM=`date +%d`		# Date of the Month e.g. 27
MONTH=`date +%b`	# Just the month name, e.g. Aug

for FS in $FILESYSTEMS; do

	# change slashes to underscores so that we can use the
	# file system names as folder names
	# only minimal protection but hopefully people won't put
	# totally outlandish paths in FILESYSTEMS
	FSSAFE=`echo $FS | tr '/' '_'`

  ONEFS="-x"

  if [ "$FS" = "." ] ; then
     FS=/
     unset ONEFS
  fi

	DUREP_TODAY="$DUREP_WEB_PATH/$FSSAFE/$DOW"

	if [ $DEBUG = "on" ]; then

		echo "FS \"$FS\""
		echo "DOM \"$DOM\""
		echo "MONTH \"$MONTH\""
		echo "DUREP_TODAY \"$DUREP_TODAY\""
		echo "DUREP_WEB_PATH/FSSAFE/MONTH \"$DUREP_WEB_PATH/$FSSAFE/$MONTH\""
		echo "."
	
	else

		mkdir -p $DUREP_TODAY

		# -n option is needed to replace existing link
		# because otherwise it creates the link inside
		# the directory that Latest refers to
		# arcane stuff this - see "info ln"
		ln -nsf "./$DOW" $DUREP_WEB_PATH/$FSSAFE/Latest

		$DUREP -td 2 -hs $SIZE_CUTOFF -w $DUREP_TODAY $ONEFS $FS \
			> $DUREP_TODAY/Summary.txt
    
    (cd $DUREP_TODAY ; $POSTEXEC)

		if [ $DOM = "01" ]; then # monthly snapshot
			# being careful here not to create lots of duplicate
			# subfolders if this script gets run more than once on
			# the first day of the month
			mkdir -p $DUREP_WEB_PATH/$FSSAFE/$MONTH

			# --target-directory option is presumably only
			# in GNU cp
			cp -urp \
			--target-directory=$DUREP_WEB_PATH/$FSSAFE/$MONTH \
			$DUREP_TODAY/*
		fi
	
	fi

done
