#!/bin/sh

. /opt/etc/functions.openrc

LOGROOT=/var/log
BACKUPDIR=/root/syslog-backup
BFPREFIX="var-log"

#
# This script can only be used for non-critical logs!
# There is a substantial hole between sync & truncation.
#
# It is better to call this script once a week.
#

DATESTAMP=$(date "+%Y-%m-%d")
OUTDIR="${BACKUPDIR}/${BFPREFIX}.${DATESTAMP}"

check_create_targets()
{
	if ! [ -d "${LOGROOT}" ]; then
		update_me
		echo "${ME}: bad source dir ${LOGROOT}, aborting rotation of logs!"
		return 1
	fi
	if [ -d "${OUTDIR}" ]; then
		update_me
		echo "${ME}: target dir ${OUTDIR} already exists, aborting rotation of logs!"
		return 1
	fi
	if [ -f "${OUTDIR}.tar.xz" ]; then
		update_me
		echo "${ME}: target archive ${OUTDIR}.tar.xz already exists, aborting rotation of logs!"
		return 1
	fi
	if ! [ -x $(which rsync) ]; then
		update_me
		echo "${ME}: rsync not found, aborting rotation of logs!"
		return 1
	fi
	mkdir -p ${OUTDIR}
	if ! [ -d "${OUTDIR}" ]; then
		update_me
		echo "${ME}: unable to create ${OUTDIR}, aborting rotation of logs!"
		return 1
	fi
	return 0
}

check_create_targets || exit 1
# Slow pass
rsync -a ${LOGROOT}/ ${OUTDIR}
# Fast pass
rsync -a ${LOGROOT}/ ${OUTDIR}
# Truncate the logs
find "${LOGROOT}" -type f -exec truncate --size=0 {} \;
# Archive the copy
cd ${BACKUPDIR}
tar Jcf "${BFPREFIX}.${DATESTAMP}.tar.xz" "${BFPREFIX}.${DATESTAMP}"
rm -rf "${BFPREFIX}.${DATESTAMP}"
