#!/bin/sh -fu

if [ $# -gt 2 ]; then
    echo "Usage: ${0##*/} [<filter-name>] [default-status]" >&2
    exit 1
fi

filter="${1:-}"
default_status="${2:-OK}"

. /bin/shell-source

PIDFILE=/run/nagwad.pid
CONFDIR=/etc/nagwad
LOGDIR=/var/log/nagwad

source_if_exists "$CONFDIR"/nagwad.conf
source_if_exists /etc/sysconfig/nagwad

if [ -z "$filter" ]; then
    # Check nagwad service status.
    if sd_booted; then
	if ! nagwad_status="$(systemctl is-active nagwad.service)"; then
	    echo "CRITICAL: Nagwad service isn't running! The unit state is '$nagwad_status'."
	    exit 2
	fi
    fi

    if [ -n "$PIDFILE" ]; then
	if [ ! -e "$PIDFILE" ]; then
	    echo "CRITICAL: Nagwad service isn't running! PID-file doesn't exist."
	    exit 2
	fi

	if ! pgrep -F "$PIDFILE" -L -r R,S 1>/dev/null 2>&1
	then
	    echo "CRITICAL: Nagwad service isn't running! No running process is found for $PIDFILE."
	    exit 2
	fi
    fi

    echo "OK: Nagwad service seems to work."
    exit 0
fi

check_status()
{
        case "$1" in
                OK)
                        return 0
                        ;;
                WARNING)
                        return 1
                        ;;
                CRITICAL)
                        return 2
                        ;;
                UNKNOWN)
                        return 3
                        ;;
        esac

        return 2
}

find_problem()
{
        local status="${1:-}"
        find "$LOGDIR" \
             -maxdepth 1 \
             ! -type d \
	     ! -name '*.FIXED' \
             -name "*$status" \
             -printf "%T+ %p\n" 2>/dev/null | \
            sort | \
            tail -1 | \
            cut -d' ' -f2
}

boot_id="$(cat /proc/sys/kernel/random/boot_id)"
if [ -z "$boot_id" ]; then
    echo "CRITICAL: Unable to get the current boot ID!"
    exit 2
fi

LOGDIR_BASE="$LOGDIR"
LOGDIR="${LOGDIR_BASE%/}/$boot_id/$filter"

PROBLEM=
if [ -d "$LOGDIR" ]; then
        PROBLEM="$(find_problem '.CRITICAL')"
        [ -n "$PROBLEM" ] || \
                PROBLEM="$(find_problem '.WARNING')"
        [ -n "$PROBLEM" ] || \
                PROBLEM="$(find_problem '.UNKNOWN')"
        [ -n "$PROBLEM" ] || \
                PROBLEM="$(find_problem)"
fi

if [ -z "$PROBLEM" ]; then
    message="$default_status: Nothing detected for '$filter'"
    echo "$message"
    check_status "$default_status"
else
    cat "$PROBLEM"
    check_status "${PROBLEM##*.}"
fi
