#!/bin/sh -

# Note: starthttpd is required in the PATH
PATH="/usr/ucb:/usr/bsd:/bin:/usr/bin:$PATH:$HOME/bin:$HOME/httpd/bin"
export PATH

# The locations of the access log files
alogs="$HOME/httpd/logs/access_log $HOME/httpd/logs/agent_log"\
" $HOME/httpd/logs/referer_log"
# Access log files that should be archived sorted and counted
clogs="$HOME/httpd/logs/agent_log $HOME/httpd/logs/referer_log"

# The location of the error log file
elog="$HOME/httpd/logs/error_log"

# A grep pattern identifying non-error lines in the error log file
epatt=': Starting'	# this pattern works for NCSA HTTPd 1.5

# The depth of subdirectories to use in the log archive directory
# "monthly", "yearly" or "none"
subdirs=none

# The compression command to use
compress='compress -f'

# The user that should own the rolled logs, if any
user=

####################### End Custom Configuration ##############################

# rolllogs - rollover NCSA-style HTTPd log files
# Steve Kinzler, steve@kinzler.com, Mar 94/Sep 94/Mar 96
# https://kinzler.com/me/home.html#webadm

access=; error=; bad=

while :
do
	case $# in
	0)	break;;
	*)	case "$1" in
		-a)	access=t;;
		-e)	error=t;;

		--)	shift; break;;
		-h)	bad=t; break;;
		-?*)	bad=t; echo "$0: unknown option ($1)" 1>&2;;
		*)	break;;
		esac
		shift;;
	esac
done

case "$#,$bad" in
0,)	;;
*)	cat << EOF 1>&2
usage: $0 [ -a ] [ -e ]
	-a	rollover the access logs (access, agent, referer)
	-e	output and truncate the error log
Without either option, all logs are handled.  Access logs are rolled
over to a subdirectory of the same name as the log with an "s" appended,
into a compressed file named with the date of the rollover.
EOF
	exit 1;;
esac

case "$access$error" in
'')	access=t; error=t;;
esac

case "$subdirs" in
monthly)	set "/`date +%y/%m`" "`date +%d`";;
yearly)		set "/`date +%y`" "`date +%m%d`";;
*)		set '' "`date +%y%m%d`";;
esac

day="`echo $1$2 | sed 's,/,,g'`"
case "$day" in
??????)	;;
*)	echo "$0: cannot determine date ($day)" 1>&2; exit 2;;
esac

case "$access" in
?*)	for alog in $alogs
	do
		if test -s "$alog"
		then
			alogdir="${alog}s$1"
			trap '' 1 2 13 15

			mkdir -p "$alogdir" 2> /dev/null
			mv "$alog" "$alogdir/$2" &&
			starthttpd -r		 &&
			case " $clogs " in
			*" $alog "*)	sort "$alogdir/$2" | uniq -c |
					    sed 's/^[ 	]*//' \
						> "$alogdir/$2.tmp" &&
					rm "$alogdir/$2"	    &&
					mv "$alogdir/$2.tmp" "$alogdir/$2";;
			*)		true;;
			esac			 &&
			$compress "$alogdir/$2"

			case "$user" in
			?*)	chown "$user" "$alogdir/$2"*
				while :
				do
					chown "$user" "$alogdir"
					case "$alogdir" in
					"${alog}s"|'')	break;;
					esac
					alogdir=`echo "$alogdir" |
						 sed 's/\/*[^\/]*$//'`
				done;;
			esac

			trap exit 1 2 13 15
		fi
	done;;
esac

case "$error" in
?*)	if grep -s -v "$epatt" "$elog" > /dev/null 2>&1
	then
		trap '' 1 2 13 15

		mv  "$elog" "$elog.$day" &&
		starthttpd -K		 &&
		cat "$elog.$day"	 &&
		rm  "$elog.$day"

		trap exit 1 2 13 15
	fi;;
esac
