#!/bin/sh
#
# Copyright © 2017-2019 Andreas Beckmann (anbe@debian.org)
# Copyright © 2018 Holger Levsen (holger@layer-acht.org)
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see <https://www.gnu.org/licenses/>

#
# * rotate master logfiles greater than 1 MB
# * (delayed) compress rotated master logs
#

. /usr/share/piuparts/lib/read_config.sh
. /usr/share/piuparts/lib/write_log.sh

get_config_value SECTIONS global sections
get_config_value MASTER global master-directory
get_config_value HTDOCS global output-directory

today=$(date +%Y%m%d)
OUTPUT=$(mktemp)

cd $MASTER
for SECTION in $SECTIONS ; do
	mlog=$SECTION/master.log
	rlog=$SECTION/master.$today.log

	# rotate master.log larger than 1 MB
	if [ -f $mlog ] && [ ! -L $mlog ] && [ $(stat -c %s $mlog) -gt 1048576 ] && [ ! -e $rlog ]; then
		mv -v $mlog $rlog >> $OUTPUT
	fi

	# delayed compression of old master.log
	for log in $SECTION/master.*.log
	do
		if [ -f "$log" ] && [ "$log" != "$rlog" ]; then
			xz -v9 $log >>$OUTPUT 2>&1
		fi
	done

	# delete master logs older than 90 days, but keep at least five old logs
	oldlogs=$(ls -t1 $SECTION/master.*.log.* 2>/dev/null | tail -n +5)
	if [ -n "$oldlogs" ]; then
		find $oldlogs -mtime +90 | xargs -r rm -fv >>$OUTPUT 2>&1
	fi
done

LOGDATEDIR="$HTDOCS/logs/$(date -u '+%Y/%m/%d' -d '7 days ago')"
if [ -d $LOGDATEDIR ] && [ -n "$(find $LOGDATEDIR -type f ! -name '*.xz')" ] ; then
	echo >> $OUTPUT
	echo "Compressing old piuparts.d.o logfiles." >> $OUTPUT
	echo >> $OUTPUT
	find $LOGDATEDIR -type f ! -name '*.xz' -exec xz -v9 {} \; >>$OUTPUT 2>&1
fi

if [ -s $OUTPUT ] ; then
	LOG_OUTPUT=$(mktemp)
	echo "$(date -u)" > $LOG_OUTPUT
	echo >> $LOG_OUTPUT
	cat $OUTPUT >> $LOG_OUTPUT
	echo >> $LOG_OUTPUT
	publish_logs $LOG_OUTPUT "" $HTDOCS rotate_master_logs
fi
rm $OUTPUT
