#!/bin/bash

LANG=C
LC_ALL=C
DMESG_CMD="dmesg --level=err"
STATUS_FILE="/var/cache/ee/check_dmesg.status"
CONFIG_FILE="/etc/nagios-plugins/check_dmesg.whitelist"
LOCAL_CONFIG_FILE="/etc/nagios-plugins/check_dmesg.local.whitelist"


usage() {
	echo "Usage : $0 [-h] [init]"
	echo "  -h    Display this message"
	echo "  init  Save current status to $STATUS_FILE"
}

[[ "$1" == "-h" ]] && usage && exit 0

get_status() {
    $DMESG_CMD || exit 3
}

mkdir -p "$(dirname $STATUS_FILE)" || exit 3
touch "$STATUS_FILE"

if [[ "$1" == "init" ]]; then
    get_status > $STATUS_FILE || exit 3
    echo "Current status saved in $STATUS_FILE"
    exit 0
fi

TMP=$(mktemp)
get_status > "$TMP"
new_status=$(comm -1 -3 --nocheck-order "$STATUS_FILE" "$TMP")
rm -f "$TMP"

[[ ! -f "$CONFIG_FILE" ]] && echo "$CONFIG_FILE not found" && exit 3
whitelist=$(cat "$CONFIG_FILE")

if [[ -e "$LOCAL_CONFIG_FILE" ]]; then
    whitelist+=$'\n'
    whitelist+="$( cat "$LOCAL_CONFIG_FILE" )"
fi

whitelist=$(grep -vE '^\s*(#|$)' <<< "$whitelist")

while IFS="" read -r l || [[ -n "$l" ]]; do
    new_status=$(echo "$new_status" | grep -Ev "$l")
done <<< "$whitelist"

if [[ -z "$new_status" ]]; then
   echo "OK : dmesg contains no unhandled errors"
   exit 0
fi

TMP=$(mktemp)
echo "$new_status" > "$TMP"
pretty_new_status=$(dmesg -T -F "$TMP" || exit 3)
rm -f "$TMP"

echo "WARNING : dmesg contains unhandled errors."
echo "Doc: https://www.easter-eggs.fr/ee/admins/supervision/check_dmesg"
echo "To mark these errors as handled, run '$(realpath "$0") init'."
echo
echo -e "$pretty_new_status"
exit 1
