#!/usr/bin/env -S chronic bash

set -e
umask 077

STAMPFILE=$HOME/.journal-checker.stamp

if [[ ! -f $STAMPFILE ]]; then
    SINCE="--this-boot"
else
    SINCE="--since=$(head -n1 $STAMPFILE)"
fi

# just ignore cretain error messages
filter() {
    grep -v 'systemd-tmpfiles\[[0-9]*\]: Detected autofs mount point /home during canonicalization of /home.$' | \
    grep -v 'systemd-xdg-autostart-generator\[[0-9]*\]:' | \
    grep -v 'dhcpd\[[0-9]*\]: uid lease [0-9.]* for client [0-9a-f:]* is duplicate on [0-9.]*/[0-9]*$' | \
    grep -v 'sshd\[[0-9]*\]: error: kex_exchange_identification: \(Connection closed by remote host$\|read: Connection reset by peer$\|client sent invalid protocol identifier\)' | \
    grep -v 'sshd\[[0-9]*\]: error: maximum authentication attempts exceeded for root from [0-9.]* port [0-9]* ssh2 \[preauth\]$' | \
    grep -v 'sshd\[[0-9]*\]: error: kex_exchange_identification: banner line contains invalid characters$' | \
    grep -v 'postfix/smtpd\[[0-9]*\]: warning: hostname .*[.]nbox-tv[.]priv does not resolve to address 192.168.5.[0-9]*: Name or service not known$' | \
    grep -v 'sudo\[[0-9]*\]: pam_krb5(sudo:setcred): (user [a-z0-9]*) credential reinitialization in a setuid context ignored$' \
    grep -v 'gsd-power\[[0-9]*\]: Error calling suspend action'
}

NOW=$(date +"%Y-%m-%d %H:%M")
LOG=$(mktemp --tmpdir .journal-checker.XXXXXX.log)
trap "rm -f $LOG" EXIT QUIT TERM
journalctl -oshort-iso-precise --full --no-pager -p warning "$SINCE" | filter | tee $LOG

ERRORS=$(cat $LOG | fgrep -v -- '-- No entries --' | fgrep -v -- '-- Journal begins at ' | wc -l)
echo "($ERRORS errors)"

if [[ $ERRORS -gt 0 ]]; then
    RC=1
else
    RC=0
fi

echo $NOW > $STAMPFILE
exit $RC

# vim: ft=bash
