#!/bin/bash

# Copyright 2004 Jacob Joseph<jacob@jjoseph.org>
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

KEY=$1
REMOTE=$2
PLUGIN=$3
shift
shift
shift
PLUGIN_OPTS=$*

#KEY=/etc/nagios/id_rsa
#REMOTE="jacob@lunch.nuke"
#PLUGIN=check_vsz.py
#PLUGIN_OPTS="-w 10000 -c 2000000"

help() {
[ -n "$1" ] && echo "ERROR: $1"

echo "Copyright 2004 Jacob Joseph 
Distributed under the GNU General Public License, version 2 or higher

This Nagios plugin is designed to push a plugin across an ssh session,
run it, and return the remote plugin's return code.  Only an ssh
account and home directory are required of the remote machine.  If
running on multiple architectures, be sure the plugin is compatible
with the remote machine.

Usage: check_remote.sh <user>@<remote host> <plugin> <plugin options>"
exit -1
}

check_args() {
    [ -z "$KEY" ] && help "KEY is null"
    [ -z "$REMOTE" ] && help "REMOTE is null"
    [ -z "$PLUGIN" ] && help "PLUGIN is null"
    [ ! -e "$KEY" ] && help "SSH key: '$KEY' does not exist"
    [ ! -e "$PLUGIN" ] && help "Plugin: '$PLUGIN' does not exist"

}

run_plugin() {
    loc_md5=$(md5sum $PLUGIN|cut -d' ' -f1)
    #echo "loc_md5: $loc_md5"
    rem_plugin=$(basename $PLUGIN)

    ssh_session=$(ssh -q -o "StrictHostKeyChecking no" -i $KEY $REMOTE "
rem_md5=\$(md5sum $rem_plugin 2>&1|cut -d' ' -f1)

if [ "$loc_md5." == "\$rem_md5." ]; then
    rem_out=\$(./$rem_plugin $PLUGIN_OPTS)
    rem_ret=\$?

    echo "... \$rem_out ... \$rem_ret"
else
    echo "... BAD_MD5 ... -3"
fi
")

    rem_out=$(echo "$ssh_session"|sed -ne "s/\.\.\. \(.*\) \.\.\. .*/\1/p")
    rem_ret=$(echo "$ssh_session"|sed -ne "s/\.\.\. .* \.\.\. \(.*\)/\1/p")
}

push_plugin() {
    scp -q -o "StrictHostKeyChecking no" -i $KEY $PLUGIN $REMOTE:
}

# declare a few variables
rem_out=""
rem_ret=""

check_args
run_plugin

# do we need to update?
if [ "$rem_ret" -eq "-3" ]; then
    push_plugin
    run_plugin
fi

echo "$rem_out"
exit $rem_ret


