#!/bin/sh

UNKNOWN=3

cmd=
hostname=
timeout=10

while getopts c:h:t: name
do
    case $name in
        c) cmd=$OPTARG ;;
        h) hostname=$OPTARG ;;
        t) timeout=$OPTARG ;;
    esac
done

if [ -z "$cmd" ]
then
    echo 'check_by_sshmon: Option "-c $cmd" missing' >&2
    exit $UNKNOWN
fi

if [ -z "$hostname" ]
then
    echo 'check_by_sshmon: Option "-h $hostname" missing' >&2
    exit $UNKNOWN
fi

timeout "$timeout" \
    ssh sshmon@"$hostname" \
        -o IdentityFile=/etc/sshmon.priv \
        -o StrictHostKeyChecking=accept-new \
        -o ControlMaster=auto \
        -o ControlPath=~/master-%C \
        -o ControlPersist=30m \
        -o HashKnownHosts=no \
        "$cmd"
exitcode=$?

if [ "$exitcode" = 124 ]
then
    echo 'check_by_sshmon: Timeout while running check remotely' >&2
    exit $UNKNOWN
elif [ "$exitcode" = 255 ]
then
    echo 'check_by_sshmon: SSH error' >&2
    exit $UNKNOWN
else
    exit $exitcode
fi
