#!/bin/sh
############################################################ IDENT(1)
#
# $Title: Script to rotate log files $
# $Copyright: 2022 Devin Teske. All rights reserved. $
# $FrauBSD$
#
############################################################ PROGRAM

pgm="${0##*/}" # Program basename
_pgm="${pgm%-*}" # Program suite

############################################################ CONFIGURATION

LOGFILE="/var/log/$_pgm/$_pgm.log"
NLOGFILES=14

############################################################ GLOBALS

#
# Global exit status
#
FAILURE=1

############################################################ FUNCTIONS

quietly(){ "$@" > /dev/null 2>&1; }

usage()
{
	local fmt="$1"
	local optfmt="\t%-5s %s\n"
	exec >&2
	if [ "$fmt" ]; then
		shift 1 # fmt
		printf "%s: $fmt\n" "$pgm" "$@"
	fi
	printf "Usage: %s [-h]\n" "$pgm"
	printf "Options:\n"
	printf "$optfmt" "-h" "Print usage statement and exit."
	exit $FAILURE
}

############################################################ MAIN

#
# Process command-line options
#
while getopts h flag; do
	case "$flag" in
	*) usage # NOTREACHED
	esac
done
shift $(( $OPTIND - 1 ))

#
# Check command-line arguments
#
[ $# -eq 0 ] || usage "Too many arguments" # NOTREACHED

#
# Rotate
#
quietly rm -f "$LOGFILE.$NLOGFILES.gz"
n=$NLOGFILES
while [ $n -ge 0 ]; do
	n=$(( $n - 1 ))
	quietly mv "$LOGFILE.$n.gz" "$LOGFILE.$(( $n + 1 )).gz"
done
quietly cp -f "$LOGFILE" "$LOGFILE.0"
quietly gzip "$LOGFILE.0"

#
# Truncate
#
:> "$LOGFILE"

################################################################################
# END
################################################################################
