#!/bin/sh
### hlmrotate.sh  -*- Sh -*-
## Rotate a set of files when any of them hit high watermark size.

### Ivan Shmakov, 2018, 2021

## To the extent possible under law, the author(s) have dedicated
## all copyright and related and neighboring rights to this software
## to the public domain worldwide.  This software is distributed
## without any warranty.

## You should have received a copy of the CC0 Public Domain Dedication
## along with this software.  If not, see
## <http://creativecommons.org/publicdomain/zero/1.0/>.

### Code:
set -e
set -C -u

verbose_p=
case "${1:-}" in
    (-v | --verbose) verbose_p=yes ; shift ;;
esac
case "${1:-}" in
    (--) shift ;;
esac

if ! test "$#" -ge 1 ; then
    printf %s\\n "Usage: ${0} [--] LOGFILE..." >&2
    ## .
    exit 1
fi

: "${ROTATE_HIMARK:=7M}"
: "${ROTATE_LOMARK:=255k}"
: "${ROTATE_SAVELOG:=savelog -r .old -lptn -d -D %FT%TZ}"
: "${ROTATE_COMMAND0:=true no _command0 set}"
: "${ROTATE_COMMAND:=true no _command set}"

test -n "$(TZ=UTC find "$@" -maxdepth 0 -size +"$ROTATE_HIMARK" 2> /dev/null)" \
    || exit 0

test -n "$verbose_p" \
    && set -x

## NB: find may fail if some of the files do not exist for some reason
find "$@" -maxdepth 0 -size +"$ROTATE_LOMARK" \
    -exec ${ROTATE_SAVELOG} -- {} + \
    || : FAIL\? "$?"

${ROTATE_COMMAND0}

## .
exec ${ROTATE_COMMAND}

### hlmrotate.sh ends here
