#!/bin/bash
#
# Copyright (C) 2009-2012:
#    Gabes Jean, naparuba@gmail.com
#    Gerhard Lausser, Gerhard.Lausser@consol.de
#    Gregory Starck, g.starck@gmail.com
#    Hartmut Goebel, h.goebel@goebel-consult.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken.  If not, see <http://www.gnu.org/licenses/>.


# Wrapper script to call Arbiter instead of Nagios bin
DIR=$(dirname "$0")


### find last python version
versions="2.4 2.5 2.6 2.7"
LASTFOUND=""
# is there any python here?
for v in $versions
do
    which python$v > /dev/null 2>&1
    if [ $? -eq 0 ]
    then
        LASTFOUND="python$v"
    fi
done

if [ -z "$LASTFOUND" ]
then
    # finaly try to find a default python
    which python > /dev/null 2>&1
    if [ $? -ne 0 ]
    then
        echo "No python interpreter found!"
        exit 2
    else
        echo "python found"
        LASTFOUND=$(which python)
    fi
fi
PY=$LASTFOUND


### usage
function usage(){
    echo "Shinken"
    echo "License: GNU AFFERO GENERAL PUBLIC LICENSE version 3"
    echo ""
    echo "Website: http://www.shinken-monitoring.org"
    echo "Usage: nagios [options] <main_config_file>"
    echo ""
    echo "Options:"
    echo ""
    echo "  -v, --verify-config          Verify all configuration data"
    echo "  -s, --test-scheduling        Not used "
    echo "  -x, --dont-verify-paths      Not used"
    echo "  -p, --precache-objects       Not used"
    echo "  -u, --use-precached-objects  Not used"
    echo "  -d, --daemon                 Not used"
}

if [ -z "$1" ]; then
    usage
    exit 0
fi


### parse args
COMMAND=""
while getopts "v:sxpud" opt; do
    case $opt in
        v)
            COMMAND="$opt"
            ARG_OPT_v="$OPTARG"
            ;;

        s|x|p|u|d)
            # ignore unused options
            ;;

        *)
            usage
            exit 0
            ;;
    esac
done
shift $(( OPTIND - 1 ))


### run commands
case "$COMMAND" in
    v)
        if [ -z "$ARG_OPT_v" ]; then
            echo "You must provide a nagios configuration file"
            exit 2
        else
	    # well shinken arbiter does not act really as nagios so we need to provide at least a -c argument for configfile
	    $PY $DIR/shinken-arbiter.py -v -c $ARG_OPT_v
	    exit $?
        fi
        ;;

    *)
        usage
        exit 0
        ;;
esac
