#!/bin/bash
#                 /usr/local/bin/rsnapshotlimit.faerie
# http://kahealani.net/posix/bin/rsnapshotlimit.faerie
# celeste crystalfaery 2016-02-05 23:59:39+00:00
# $0 deletes old rsnapshots to alleviate disk partition full

touch /tmp/rsnapshotlimit$$ # one shot e-mail flag
let percent=`head -n 1 $HOME/.rsnapshotlimit | cut -f 1` # check soon after startup
let sleep=100-$percent

# loop forever as a daemon; checking more frequently as disk fills
while sleep "$sleep"m;do
# file_system="$(grep snapshot_root /etc/rsnapshot.conf|head -n 1|cut -f 2|sed 's/\/$//')"
# echo "$0 monitoring $file_system" 1>&2
file_system="/dev/mapper/faerie--vg-home"
# echo "$0 monitoring $file_system" 1>&2
let percent=$(df -P -T | grep $file_system | sed 's/\%.*$//g ; s/^.* //g') || exit 2

# echo "$0 percent full $percent" 1>&2
let sleep=100-$percent
if [[ $percent -gt $(head -n 1 $HOME/.rsnapshotlimit | cut -f 1) ]]
then

#	uncomment this if /var/cache/rsnapshot does not have it's own partition, but shares with the system
	/usr/local/bin/thumbnail_expire	"$sleep" &		# release the daleks

	# where are the backups we delete?
	cd `grep snapshot_root /etc/rsnapshot.conf|head -n 1|cut -f 2`				|| exit 2
	oldest=`ls -rt | head -n 1`								|| exit 3
	if [ "X$oldest" = "X" ]
	then
		if [ -f /tmp/rsnapshotlimit$$ ]
		then
			rm /tmp/rsnapshotlimit$$
			echo "Process $$ Disk Usage $percent \nFix and restart me."	| mail -s "$(basename `echo $0`) du"		root &
			#aptitude clean&			# release the hounds
			apt-get clean&				# release the hounds
		else
			#aptitude clean&			# release the hounds
			apt-get clean&				# release the hounds
		fi
	else
		echo	remove	"$oldest"	| mail -s "$(basename `echo $0`) $oldest"	root &
		rm	-rf	"$oldest"	# Delete the oldest backup
	fi
fi
if [[ $sleep -lt 1 ]]
then
	let sleep=1	# minimum sleep time
fi
done
&& exit 0											|| exit 4
echo "rsnapshots: `ls $(grep snapshot_root /etc/rsnapshot.conf|head -n 1|cut -f 2) | grep -v lost+found | tr '[\n]' ' '`"
find /etc -maxdepth 1 -name 'rsnapshotlimit' -type f -print0 -exec head -n 1 {} \; | sed 's/limit./limit:	/'
&& exit 0											|| exit 4
