#!/bin/mksh
# $MirSecuCron$
# $MirOS: src/etc/anacron,v 1.8 2009/07/18 14:08:59 tg Exp $
#-
# Copyright (c) 2007
#	Thorsten Glaser <tg@mirbsd.de>
#
# Provided that these terms and disclaimer and all copyright notices
# are retained or reproduced in an accompanying document, permission
# is granted to deal in this work without restriction, including un-
# limited rights to use, publicly perform, distribute, sell, modify,
# merge, give away, or sublicence.
#
# This work is provided "AS IS" and WITHOUT WARRANTY of any kind, to
# the utmost extent permitted by applicable law, neither express nor
# implied; without malicious intent or gross negligence. In no event
# may a licensor, author or contributor be held liable for indirect,
# direct, other damage, loss, or other issues arising in any way out
# of dealing in the work, even if advised of the possibility of such
# damage or existence of a defect, except proven that it results out
# of said person's immediate fault when using the work as intended.
#-
# schedule daily/weekly/monthly cronjobs to run if we're 3 days over

export PATH=/bin:/usr/bin:/sbin:/usr/sbin
cd /
umask 077
typeset -i minutes=15

function schedule {
	typeset what=$1

	print scheduling job $what to run in $minutes minutes
	(
		sleep $((minutes * 60))
		print running scheduled $what cronjob
		mksh /etc/cronrun -n $what
		print job $what finished with return code $?
	) &
	let minutes+=15
}

function tryjob {
	typeset job=$1
	typeset -i days=$2

	if [[ -s /var/log/$job.out ]]; then
		rm -f /var/log/$job.out.gz
		gzip -n9 /var/log/$job.out
	fi
	if [[ -s /var/log/$job.out.gz ]]; then
		chown 0:0 /var/log/$job.out.gz
		chmod 0640 /var/log/$job.out.gz
		line=$(gzip -dc /var/log/$job.out.gz | head -n 1)
		if [[ $line = @(RUNTIME=)+([0-9]).+([0-9]) ]]; then
			time=$(date +%J)
			line=${line##RUNTIME=}
			line=${line%%.*}
			time=${time%%.*}
			(( (line + days) > time )) || schedule $job
		else
			print no run-time found for job $job
			schedule $job
		fi
	else
		print no log file found for job $job
		schedule $job
	fi
}

tryjob daily 3
tryjob weekly 10
tryjob monthly 34
if (( minutes != 15 )); then
	wait
	print all jobs finished
fi
exit 0
