#!/bin/sh

#/******************************************************************************
# * Icinga 2                                                                   *
# * Copyright (C) 2012-2014 Icinga Development Team (http://www.icinga.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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.             *
# ******************************************************************************/
usage(){
cat << EOF
usage: $0 options
 This script sends check results to an icinga(2) cmd pipe.
 OPTIONS:
    -h        Show this message
    -c        External command pipe file path, e.g. '/var/run/icinga2/icinga2.cmd'
    -H        Host name for the check result
    -S        Service name for the check result. If not provided, a host check result is assumed.
    -r        Return code of the check result
    -o        Output of the checkresult
EOF
}


ECHO="/bin/echo"
CMDFILE="/var/run/icinga2/cmd/icinga2.cmd"
HOST=""
SERVICE=""
RETURNCODE=0
OUTPUT="icinga2 extcmdfile test @ `date +%s`"

while getopts ":c:H:S:r:o:h" opt; do
  case $opt in
    h)
      usage
      exit 1
      ;;
    c)
      CMDFILE=$OPTARG
      ;;
    H)
      HOST=$OPTARG
      ;;
    S)
      SERVICE=$OPTARG
      ;;
    r)
      RETURNCODE=$OPTARG
      ;;
    o)
      OUTPUT=$OPTARG
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      usage
      exit 1
      ;;
    :)
      echo "Option -$OPTARG requires an argument." >&2
      usage
      exit 1
      ;;
  esac
done

DATETIME=`date +%s`

if [ -z "$HOST" ]; then
  echo "Host name missing. Please use -H with a valid host name."
  usage
  exit 1;
fi

if [ -z "$SERVICE" ]; then
  CMDLINE="[$DATETIME] PROCESS_HOST_CHECK_RESULT;$HOST;$RETURNCODE;$OUTPUT"
else
  CMDLINE="[$DATETIME] PROCESS_SERVICE_CHECK_RESULT;$HOST;$SERVICE;$RETURNCODE;$OUTPUT"
fi

echo "Sending '$ECHO $CMDLINE >> $CMDFILE'"
`$ECHO $CMDLINE >> $CMDFILE`

exit 0
