#!/bin/bash
#                      /usr/local/bin/darlimit.fey
# http://crystalfaeries.net/posix/bin/darlimit.fey
# celeste:crystalfaery DARLIMIT.FEY 2021-03-28 23:00:12+00:00
# darlimit deletes old diskarchive (dar) backups to prevent disk full condition

cd /home/celeste/crystalfaeries.net/`hostname`/	# where are the .dar backups we delete?
cd -P .						# convert from symbolic to physical path
backuppartition="/dev/mapper/fae--vg-home"	# with more code we could compute this in a future version

limit=/etc/darlimit # 1st line of darlimit config file has the number percent disk partition fullness permitted (e.g. "90")

log=/var/log/darchive.log	# combined darchive log

touch /tmp/darlimit.$$	# one-shot e-mail flag to prevent runaway e-mail notices

let sleep=1; while sleep "$sleep"m
do
	let darlimit=`head -n 1 "${limit}" | cut -f 1` # re-fetch from config file in case administrator changed it while we are running
	let percent=$(/usr/local/bin/df -P -T -l | /bin/grep ${backuppartition} - | sed 's/\%.*$// ; s/^.* //') || exit 2
	let sleep=100-$percent	# sleep less the fuller we are
	if [[ $percent -gt $darlimit ]]
	then	# we have exceeded our disk usage limit
		oldest=`ls -rt $(find . -iname '*.dar' -print) | head -n 1`	|| exit 3
		if [ "$oldest" = "" ]
		then	# we have no more .dar files left to remove, what else can we free up?
			/usr/local/bin/thumbnail_expire	"$sleep" &	# spawn background task to free diskspace in general
			if [ -f /tmp/darlimit.$$ ]
			then	# one shot e-mail flag exists, this is our one shot to notify administrator
				rm /tmp/darlimit.$$
				echo	"Process $$ Disk Usage: $percent: touch /tmp/darlimit.$$ to reenable e-mail notification." \
			|	mail -s "$(hostname):$(basename $0) OUT OF DISK SPACE" root &
				#aptitude autoclean	# first level package cleaning
				apt-get autoclean	# first level package cleaning
				#aptitude clean		# second level package cleaning
				apt-get clean		# second level package cleaning
			else	# one shot e-mail flag is gone, we already notified the administrator
				# we are now out of disk space and are out of ways to free up space
				# at this point our only remaining option is to kill the darchive process eating disk
				echo	"`/usr/local/bin/now` $0 killing dar for lack of diskspace"	>> ${log}
				echo	"`/usr/local/bin/now` $0 killing dar for lack of diskspace"	|& mail -s "$(hostname):$(basename $0) darchive killed." root &
				pkill dar		# so long, farewell, goodbye
				touch /tmp/darlimit.$$	# one shot e-mail flag re-enabled for next dar execution
			fi
		else	# we have .dar files we can remove
			rm		"$oldest"
			echo	"removed $oldest"	>> "${log}"	# log the removal if uncommented, and/or e-mail:
#			echo	"removed $oldest"	| mail -s "$(hostname):$(basename $0) removed $oldest" root &
		fi
	fi	
	if [[ $sleep -lt 1 ]]
	then
		let sleep=1	# minimum sleep time so somebody besides me can also run
	fi
done

