#!/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

# Support two payload modes:
#   1. Inline:  "cmd:<remote-command>"  - command embedded directly.
#   2. File:    "/path/to/payload.sh"   - command read from a file.
if [[ "$payload" == cmd:* ]]; then
  remote_cmd="${payload#cmd:}"
elif [[ -r "$payload" ]]; then
  remote_cmd=$(cat "$payload")
else
  echo "UNKNOWN - vexor_ssh_check: payload file not readable: $payload"
  exit 3
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
