#!/bin/bash
# check_uptime - system uptime (Nagios/NRPE plugin).
# Usage: check_uptime [-w <min_seconds>] [-c <min_seconds>]
# Always OK unless -w/-c given, in which case it WARNs/CRITs when the host
# has been up LESS than the threshold (i.e. a recent/unexpected reboot).
set -u
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:${PATH:-}"
warn=""; crit=""
while getopts "w:c:h" o; do
    case "$o" in
        w) warn=$OPTARG ;;
        c) crit=$OPTARG ;;
        h) echo "Usage: $(basename "$0") [-w sec] [-c sec]"; exit 3 ;;
        *) echo "UNKNOWN: bad option"; exit 3 ;;
    esac
done

[ -r /proc/uptime ] || { echo "UNKNOWN: cannot read /proc/uptime"; exit 3; }
up=$(cut -d. -f1 /proc/uptime)
[ -n "${up:-}" ] || { echo "UNKNOWN: cannot parse uptime"; exit 3; }

d=$(( up / 86400 ))
h=$(( up % 86400 / 3600 ))
m=$(( up % 3600 / 60 ))
pretty=""
[ "$d" -gt 0 ] && pretty="${d}d "
pretty="${pretty}${h}h ${m}m"

perf="uptime=${up}s;${warn};${crit};0;"

if [ -n "$crit" ] && [ "$up" -lt "$crit" ]; then
    echo "CRITICAL: up $pretty (recent reboot) | $perf"; exit 2
fi
if [ -n "$warn" ] && [ "$up" -lt "$warn" ]; then
    echo "WARNING: up $pretty (recent reboot) | $perf"; exit 1
fi
echo "OK: up $pretty | $perf"; exit 0
