#!/bin/sh
#
# daily - daily cleanup of the system.

test -d /usr/adm || exit
cd /usr/adm || exit

#
# Last run must be more than 12 hours ago.
#
timestamp=daily.lasttime
test -f $timestamp && \
	test `stat -mtime $timestamp` -gt \( `date +%s` - 43200 \) && exit
>$timestamp

#
# Remove three day old files from various tmp dirs.
#
cleantmp -3 /tmp /usr/tmp /usr/preserve /usr/spool/lpd /usr/spool/at/past

#
# Truncate log files in /usr/adm.
#
test -d oldlog && { mv oldlog old || exit; }	# Old name for "old".
test -d old || mkdir old || exit

cycle()
{
	# Cycle a log file if larger than a size in kilobytes.
	local size="`expr "$1" + "$1"`"
	local log="$2"

	if test -f "$log" && test -n "$(find "$log" -size +"$size")"
	then
		test -f "old/$log.2" && cp -p "old/$log.2" "old/$log.3"
		test -f "old/$log.1" && cp -p "old/$log.1" "old/$log.2"
		cp -p "$log" "old/$log.1"
		: > "$log"
	fi
}

cycle 100 wtmp 
cycle 100 log 
cycle  20 ftplog
cycle 200 aftplog

#
# Make copies of /etc/passwd and /etc/shadow if they have been changed.
#
for file in passwd shadow
do
	if cmp -s /etc/$file old/$file.1
	then
		# Fine.
	else
		test -f old/$file.2 && cp -p old/$file.2 old/$file.3
		test -f old/$file.1 && cp -p old/$file.1 old/$file.2
		test -f /etc/$file && cp -p /etc/$file old/$file.1
	fi
done

#
# Check the mail queue for errors, cycle mail logs, and perform a queue run.
#
if [ -d /usr/spool/smail ]
then
	/usr/lib/smail/checkerr
	/usr/lib/smail/savelog /usr/spool/smail/log/logfile
	/usr/lib/smail/savelog /usr/spool/smail/log/paniclog
	cleantmp -14 /usr/spool/smail
fi
runq

#
# Continue with opt and local scripts (if any).
#
if [ -f /usr/lib/packages ]
then
	IFS=/
	while read package rest <&9
	do
		daily="/opt/$package/etc/daily"
		test -f "$daily" && sh "$daily" 9<&-
	done 9</usr/lib/packages
fi
test -f /usr/local/etc/daily && sh /usr/local/etc/daily
exit 0
