#!/bin/bash
# vexor_ssh_check - Runs a remote command via check_by_ssh, reading the
# remote payload from a file. This avoids Naemon $-macro mangling of the
# remote command, since Naemon only sees the static payload-file path.
#
# Usage:
#   vexor_ssh_check <host> <user> <port> <credfile|->|<keyfile> <auth-mode> <payload-file>
#
#   auth-mode: "pw"   -> credfile contains password (use sshpass -f)
#              "key"  -> credfile is an SSH private key path
#              "none" -> no auth (key from agent, etc.)
#
# Exit codes propagate from check_by_ssh.

set -u

if [[ $# -lt 6 ]]; then
  echo "UNKNOWN - vexor_ssh_check: usage: <host> <user> <port> <credfile> <pw|key|none> <payload-file>"
  exit 3
fi

host=$1
user=$2
port=$3
cred=$4
mode=$5
payload=$6

# Inline form: 6th arg may be a single quoted string prefixed with "cmd:" so
# the command is visible in naemon config / GUI instead of hidden inside a
# payload .sh file. This works only when the remote command contains no $
# (otherwise naemon's macro processor would mangle it).
if [[ "$payload" == cmd:* ]]; then
  remote_cmd=${payload#cmd:}
else
  if [[ ! -r "$payload" ]]; then
    echo "UNKNOWN - vexor_ssh_check: payload file not readable: $payload"
    exit 3
  fi
  remote_cmd=$(cat "$payload")
fi

CHECK_BY_SSH=/opt/vexor/plugins/check_by_ssh
[[ -x "$CHECK_BY_SSH" ]] || CHECK_BY_SSH=/usr/lib64/nagios/plugins/check_by_ssh

ssh_opts=(
  -t 30 -E
  -o StrictHostKeyChecking=no
  -o UserKnownHostsFile=/dev/null
  -o LogLevel=ERROR
  -o BatchMode=no
  -o ConnectTimeout=10
)

case "$mode" in
  pw)
    if [[ ! -r "$cred" ]]; then
      echo "UNKNOWN - vexor_ssh_check: password file not readable: $cred"
      exit 3
    fi
    exec /usr/bin/sshpass -f "$cred" "$CHECK_BY_SSH" \
      -H "$host" -l "$user" -p "$port" "${ssh_opts[@]}" \
      -C "$remote_cmd"
    ;;
  key)
    exec "$CHECK_BY_SSH" \
      -H "$host" -l "$user" -p "$port" -i "$cred" "${ssh_opts[@]}" \
      -C "$remote_cmd"
    ;;
  none)
    exec "$CHECK_BY_SSH" \
      -H "$host" -l "$user" -p "$port" "${ssh_opts[@]}" \
      -C "$remote_cmd"
    ;;
  *)
    echo "UNKNOWN - vexor_ssh_check: invalid mode '$mode' (expected pw|key|none)"
    exit 3
    ;;
esac
