#!/bin/bash
lock() {
    exec 903>/var/lock/fuel-logrotate
    flock -n 903 && return 0 || return 1
}

unlock() {
    flock -u 903
}

fail() {
    if [ -z "$1" ]
    then
        MESSAGE="WARNING logrotate failed, no reason provided"
    else
        MESSAGE=$1
    fi
    /usr/bin/logger -t logrotate "${MESSAGE}"
    unlock
    exit 1
}

lock || fail "WARNING logrotate flock failed, exiting"

nice ionice -c3 /usr/sbin/logrotate /etc/logrotate.d/fuel.nodaily >& /tmp/logrotate
EXITVALUE=$?

if [ -f /etc/redhat-release ] || [ -f /etc/centos-release ];
then
    # Due to bug in logrotate on centos/rhel, it always returns 0. Use grep for
    # detect errors; exit code 1 is considered a success as no errors were
    # found.
    grep -q error /tmp/logrotate
    EXITVALUE=$?
    EXPECTEDVALUE=1
else
    EXPECTEDVALUE=0
fi

if [ "${EXITVALUE}" != "${EXPECTEDVALUE}" ]; then
    fail "ALERT exited abnormally with [${EXITVALUE}] (${EXPECTEDVALUE} was expected)"
fi

unlock
exit 0
