#!/bin/bash

#VARIABLES SHINKEN
OK=0
WARNING=1
CRITICAL=2
UNKNOWN=3

PROGNAME=`basename $0 .sh`
VERSION="Version 01.10"

print_version() {
    echo "$VERSION"
}

print_help() {
    print_version $PROGNAME $VERSION
    echo ""
    echo "$PROGNAME is a Shinken plugin to check a specific content by curl."
    echo ""
    echo "$PROGNAME -u <url> -a <content_to_test> -n <name>"
    exit $UNKNOWN
}

if test -z "$1"
then
        print_help
        exit $CRITICAL
fi

# Ensuring we have the needed tools
curl=`which curl 2>/dev/null`
if [[ -z "${curl}" ]]; then
    echo "ERROR: You must have curl installed in order to run this plugin"
    exit -1
fi

# Getting parameters
while test -n "$1"; do
    case "$1" in
        --help|-h)
            print_help
            exit $UNKNOWN
            ;;
        --version|-v)
            print_version $PROGNAME $VERSION
            exit $UNKNOWN
            ;;
        --url|-u)
            URL=$2
            shift
            ;;
        --value|-a)
            VALUE=$2
            shift
            ;;
        --name|-n)
            NAME=$2
            shift
            ;;
        *)
            echo "Unknown argument: $1"
            print_help
            exit $UNKNOWN
            ;;
        esac
    shift
done

# Doing the actual check
RESULT=$(curl -s ${URL}) >/dev/null 2>&1
# Test RESULT and ECHO
if [[ "${RESULT}" ]]; then

    if [[ $RESULT == *"404 – Non trouvé"* ]]; then
        echo "UNKNOWN : 404 le rest service n'est pas disponible"
        echo "$NAME"
        exit $UNKNOWN
    else
        echo "$RESULT"
        echo "$NAME"
        exit $OK
    fi

else
    echo "UNKNOWN : $RESULT"
    echo "$NAME"
    exit $UNKNOWN
fi
