#!/bin/sh
# This is a shell script replacement for the sysklogd's logrotate cron script
# and syslogd-listfiles perl script. 
# Copyright (C) 2008-2015 N. Angelacos for the Alpine Linux project  - GPL2


CONF="/etc/syslog.conf"


syslogd_listfiles() {
	# List the target files from syslog.conf
	
	local skip=
	[ "$1" = "--auth" ]  && skip="!"

	# the while loop joins lines that end in "\"
	# the sed (in order)- 	
	#		strips comments;
	#		remove empty lines;
	#		collapses spaces/tabs to 1 space;
	#		deletes the "-" in front of the filename;
	#		deletes whitespace before ';'
	#		deletes lines that have/dont have the "auth" facility
	#		deletes the facility (leaving just the filename)
	#		deletes lines that are not filenames with leading "/"
	#		print it
	while read a ; do echo "$a"; done < $CONF |\
		sed -nE -e "s/\#.*//" \
			-e "/^[[:space:]]*$/D" \
			-e "s/[[:space:]]+/ /g" \
			-e "s: -/: /:g" \
			-e "s/ *; */;/" \
			-e "/^.*(auth)[^ ]* /${skip}D" \
			-e "s:^.* /:/:" \
			-e "/^[^\\/]/D" \
			-e "P" \
		| sort | uniq
}

# dumb little savelog  - no error checking here 
savelog () {
	local group="adm"
	local mode="644"
	local user="root"
	local cycle=2
	local logfile=""

	# parse args
	while getopts "g:u:m:c:" opt; do
		case $opt in 
			g) group=$OPTARG ;;
			u) user=$OPTARG ;;
			m) mode=$OPTARG ;;
			c) cycle=$OPTARG ;;
			*) echo "unknown option: $opt" >&2 && return 1;;
		esac
	done
	shift $(( $OPTIND - 1 ))
	logfile=$1

	# Cycle the logs
	while [ $cycle -ne 0 ]; do
		p=$cycle
		cycle=$(( $cycle - 1 ))
		a=$logfile.$cycle*
		b=$( echo $a | sed "s/\.$cycle/\.$p/") 
		[ -f $a ] && mv $a $b
	done

	# compress .1 and let .0 be uncompressed
	[ -f $logfile.1 ] && gzip $logfile.1 
	[ -f $logfile ] && mv $logfile $logfile.0

	# set permissions
	chown $user:$group $logfile.* 2>/dev/null
	chmod $mode $logfile.* 2>/dev/null
}


# Main script

for LOG in $( syslogd_listfiles ); do
	[ -f $LOG ] && savelog -g adm -m 640 -u root -c 7 $LOG
done

for LOG in $(syslogd_listfiles --auth); do
	[ -f $LOG ] && savelog -g adm -m 640 -u root -c 7 $LOG
done

killall -HUP syslogd

