#!/bin/bash
#
# Nagios plugin to check for services needing restart using the 'needrestart' package.
#
# Copyright (c) 2025, GitHub Copilot
#
# This script is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This script is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.

# Nagios exit codes
STATE_OK=0
STATE_WARNING=1
STATE_CRITICAL=2
STATE_UNKNOWN=3

# Check if needrestart is installed
if ! dpkg -s needrestart >/dev/null 2>&1; then
    echo "UNKNOWN: The 'needrestart' package is not installed."
    exit $STATE_UNKNOWN
fi

# Run needrestart in batch/list mode and grep for service lines.
# The '|| true' prevents the script from exiting if grep finds no matches.
services_to_restart=$(sudo needrestart -b -l 2>/dev/null | grep '^NEEDRESTART-SVC:' || true)

if [ -z "$services_to_restart" ]; then
    echo "OK: No services need to be restarted."
    exit $STATE_OK
else
    # Count the number of services and format the list for the output.
    num_services=$(echo "$services_to_restart" | wc -l)
    service_list=$(echo "$services_to_restart" | sed 's/NEEDRESTART-SVC: //' | tr '\n' ' ')
    echo "WARNING: $num_services service(s) need to be restarted: $service_list"
    exit $STATE_WARNING
fi
