#!/bin/bash
# check_vms — Vexor OpenVMS check plugin.
#
# Queries the local Vexor OpenVMS bridge (vexor-vms) and returns Nagios-format
# output. Naemon runs this as an active check; the bridge does the actual
# OpenVMS collection and caches the result, so this call returns instantly.
#
# Usage:
#   check_vms -n <vms-host> -c <check> [-H <bridge>] [-p <port>] [-w <warn>] [-C <crit>]
#
#   -n  OpenVMS host name as configured in the bridge (required)
#   -c  check: cpu|memory|swap|disk|network|hardware|licenses|updates|
#              processes|queues|versions|procs|users|backup|crashdump|diskintegrity|raid|performance|overview (required)
#   -H  bridge address           (default: 127.0.0.1)
#   -p  bridge port              (default: 8710)
#   -w  warning threshold        (check-specific, optional)
#   -C  critical threshold       (check-specific, optional)
#   -k  bearer token             (default: read /etc/vexor/vms/token)
#   -t  timeout seconds          (default: 10)
#
# Exit codes follow the Nagios convention (0 OK, 1 WARNING, 2 CRITICAL,
# 3 UNKNOWN), taken from the bridge's X-Nagios-Status response header.

BRIDGE="127.0.0.1"
PORT="8710"
HOST=""
CHECK=""
WARN=""
CRIT=""
TOKEN=""
TOKEN_FILE="/etc/vexor/vms/token"
TIMEOUT=10

usage() {
    sed -n '2,25p' "$0" | sed 's/^# \{0,1\}//'
    exit 3
}

while getopts "H:p:n:c:w:C:k:t:h" opt; do
    case $opt in
        H) BRIDGE="$OPTARG" ;;
        p) PORT="$OPTARG" ;;
        n) HOST="$OPTARG" ;;
        c) CHECK="$OPTARG" ;;
        w) WARN="$OPTARG" ;;
        C) CRIT="$OPTARG" ;;
        k) TOKEN="$OPTARG" ;;
        t) TIMEOUT="$OPTARG" ;;
        h) usage ;;
        *) usage ;;
    esac
done

if [ -z "$HOST" ] || [ -z "$CHECK" ]; then
    echo "UNKNOWN - missing -n <host> or -c <check>"
    exit 3
fi

# Resolve token: -k wins, else token file (if readable), else none.
if [ -z "$TOKEN" ] && [ -r "$TOKEN_FILE" ]; then
    TOKEN="$(tr -d '\r\n' < "$TOKEN_FILE")"
fi

URL="http://${BRIDGE}:${PORT}/nagios/${HOST}/${CHECK}"
QS=""
[ -n "$WARN" ] && QS="${QS}warning=${WARN}&"
[ -n "$CRIT" ] && QS="${QS}critical=${CRIT}&"
[ -n "$QS" ] && URL="${URL}?${QS%&}"

HDRS_FILE="$(mktemp /tmp/check_vms.XXXXXX)"
trap 'rm -f "$HDRS_FILE"' EXIT

AUTH=()
[ -n "$TOKEN" ] && AUTH=(-H "Authorization: Bearer ${TOKEN}")

BODY="$(curl -s -m "$TIMEOUT" -D "$HDRS_FILE" "${AUTH[@]}" "$URL")"
if [ $? -ne 0 ]; then
    echo "UNKNOWN - cannot reach Vexor OpenVMS bridge at ${BRIDGE}:${PORT}"
    exit 3
fi

HTTP_CODE="$(awk 'toupper($1) ~ /^HTTP/ {print $2}' "$HDRS_FILE" | tail -1)"
if [ "$HTTP_CODE" = "401" ]; then
    echo "UNKNOWN - bridge rejected the token (HTTP 401); check ${TOKEN_FILE}"
    exit 3
fi

EXIT_CODE="$(grep -i '^X-Nagios-Status:' "$HDRS_FILE" | tr -d '\r' | awk '{print $2}')"
if [ -z "$EXIT_CODE" ]; then
    echo "UNKNOWN - no X-Nagios-Status header from bridge (HTTP ${HTTP_CODE:-?})"
    exit 3
fi

echo "$BODY"
exit "$EXIT_CODE"
