#!/bin/bash
#                       /usr/local/bin/directory_growth
# https://crystalfaeries.net/posix/bin/directory_growth
# http://hackerpublicradio.org/eps.php?id=2113
# celeste:crystalfaery DIRECTORY_GROWTH 2017-08-02 16:50:44+00:00

# INVOCATION FROM CRON (max one per day):
#00	03	 *	 *	0	/usr/local/bin/directory_growth /
#00	03	 *	 *	1	/usr/local/bin/directory_growth /home/
#00	03	 *	 *	2	/usr/local/bin/directory_growth /home/.audacity/
#00	03	 *	 *	3	/usr/local/bin/directory_growth /home/crystalfaeries.net/
#00	03	 *	 *	4	/usr/local/bin/directory_growth /home/www/
#00	03	 *	 *	5	/usr/local/bin/directory_growth /media/celeste/TailsData/
#00	03	 *	 *	6	/usr/local/bin/directory_growth /var/

# CONFIGURATION:
DIRECTORY="${HOME}/.directory_growth"
LASTWEEK_FILE="du_$(/bin/date --date="7 days ago"	+\%Y\%m\%d)"
THISWEEK_FILE="du_$(/bin/date				+\%Y\%m\%d)"

/bin/mkdir -p						"${DIRECTORY}"				|| exit 1
cd							"${DIRECTORY}"				|| exit 2
/usr/bin/du -m -x -X "${DIRECTORY}"/exclude.txt ${1} >	"${DIRECTORY}"/"${THISWEEK_FILE}"	2> /dev/null
/bin/cp	/dev/null								   delta.sql	|| exit 4
/bin/echo "create table old (oldsize integer, path varchar);"			>> delta.sql	|| exit 4
/bin/echo "create table new (newsize integer, path varchar);"			>> delta.sql	|| exit 4
/bin/echo '.separator "\t" '							>> delta.sql	|| exit 4
/bin/echo ".import ${THISWEEK_FILE} new"					>> delta.sql	|| exit 4
/bin/echo ".import ${LASTWEEK_FILE} old"					>> delta.sql	|| exit 4
/bin/echo ".mode csv"								>> delta.sql	|| exit 4
/bin/echo ".headers on"								>> delta.sql	|| exit 4
/bin/echo ".out deltas.csv"							>> delta.sql	|| exit 4
/bin/echo "select *,newsize-oldsize as delta_in_megabytes from old natural join new where oldsize<newsize order by delta_in_megabytes desc;" \
										>> delta.sql	|| exit 4
/usr/bin/sqlite3								 < delta.sql	|| exit 5
# e-mail a textual summary of the largest dirs we monitor, and today's directory_growth deltas.csv file
cat "${DIRECTORY}"/du_*	| \
sort -nr	| uniq	| \
head -n 32		| \
/usr/bin/mailx -A deltas.csv -s "directory_growth $(/bin/hostname):${1}" $(/usr/bin/whoami)	|| exit 6
/bin/rm		${LASTWEEK_FILE}								|| exit 7



syntax highlighted by Code2HTML, v. 0.9.1