#!/bin/bash
# Nagios check to determine if specific daemontools-services are up or down.
# UNKNOWN: Service not found.
# PROBLEM: 1 or more Service(s) Down.
# OK: All services up.
# Usage: check_daemontools_services <service_name> ... <service_name> ...

services=$*

MSG=""
STATUS=-1
PROBLEM_EXIT_CODE=1

for svc in $services; do
    # add a new line if MSG already has data.
    test -n "$MSG" && MSG="${MSG}\n"

    # Make sure the service link/folder exists.
    if [ ! -e /etc/service/$svc ]; then
        # if another service already set status, leave it that way.
        test $STATUS -ne $PROBLEM_EXIT_CODE && STATUS=3
        MSG="${MSG}UNKNOWN: /etc/service/${svc}: service folder does not exist"
        continue
    fi
    svstat=$(sudo /usr/bin/svstat /etc/service/$svc)
    # set state to "up" or "down" from the svstat output.
    state=$(echo $svstat | sed -rn "s#^/etc/service/${svc}: (up|down) .*#\1#p")

    if [ "$state" = "up" ]; then
        # if another service already set status, leave it that way.
        test $STATUS -eq -1 && STATUS=0
        MSG="${MSG}OK: $svstat"
    else
        STATUS=$PROBLEM_EXIT_CODE
        MSG="${MSG}PROBLEM: $svstat"
    fi
done

# that's all.
echo -e $MSG
exit $STATUS
