#!/bin/bash
# vim: tabstop=4 shiftwidth=4 softtabstop=4 expandtab
#
# Nagios plugin to needrestart state
#
# Author: Benjamin Renard <brenard@easter-eggs.com>
# Version: 0.1
# Date: Wed, 17 Jul 2024 16:24:31 +0200
# SPDX-License-Identifier: GPL-3.0-or-later
#

DEBUG=0
MODE=all
NEEDRESTART_PATH=/usr/sbin/needrestart

function usage () {
    ERROR="$*"
    [[ -n "$ERROR" ]] && echo -e "$ERROR\n"
cat << EOF
Usage: $0 [-d] [-k | -l] [-h]
    -k          check for obsolete kernel
    -l          check for obsolete libraries
    -d          debug mode
    -h          show this message
EOF
    [[ -n "$ERROR" ]] && exit 1 || exit 0
}

function debug() {
    if [[ $DEBUG -eq 1 ]]; then
        >&2 echo -e "[DEBUG] $*"
    fi
}

while getopts "hkld" OPTION; do
    case $OPTION in
        k)
            MODE=kernel
        ;;
        l)
            MODE=services
        ;;
        d)
            DEBUG=1
        ;;
        h)
            usage
        ;;
        \?)
            usage "Unknown option '$OPTION'"
    esac
done

if [[ ! -x "$NEEDRESTART_PATH" ]]; then
    echo "UNKNOWN - needrestart not installed"
    exit 3
fi

VERSION=$( $NEEDRESTART_PATH --version |grep -E '^needrestart [0-9\.]+ - ' | awk '{print $2}' 2> /dev/null )
debug "Needrestart version: $VERSION"
if [[ -z "$VERSION" ]]; then
    echo "UNKNOWN - fail to detect needrestart version"
    exit 3
fi

CMD=( )
if [[ $( bc <<< "$VERSION >= 2.1" ) -eq 1 ]]; then
    debug "Use native needrestart -p parameter"
    CMD=( "$NEEDRESTART_PATH" -p )
    case $MODE in
        kernel)
            CMD+=( -k )
            ;;
        services)
            CMD+=( -l )
            ;;
    esac
else
    debug "Needrestart do not support -p parameter, use check_needrestart_legacy"
    CHECK_NEEDRESTART_LEGACY_PATH=
    for path in /usr/local/lib/nagios/plugins /usr/lib/nagios/plugins; do
        if [[ -e "$path/check_needrestart_legacy" ]]; then
            CHECK_NEEDRESTART_LEGACY_PATH="$path/check_needrestart_legacy"
            break
        fi
        debug "check_needrestart_legacy not found in $path"
    done

    if [[ -z "$CHECK_NEEDRESTART_LEGACY_PATH" ]]; then
        echo "UNKNOWN - check_needrestart_legacy not found"
        exit 3
    fi

    CMD=( "$CHECK_NEEDRESTART_LEGACY_PATH" )
    case $MODE in
        kernel)
            CMD+=( --no-libraries )
            ;;
        services)
            CMD+=( --no-kernel )
            ;;
    esac
fi

debug "Execute '${CMD[*]}'"
OUTPUT=$( "${CMD[@]}" 2>&1 )
RES=$?

# Change critical output to warning
if [[ $RES -eq 2 ]]; then
    echo -e "${OUTPUT/#CRIT - /WARN - }"
    exit 1
fi

echo -e "$OUTPUT"
exit $RES
