#!/bin/bash
# File: /usr/lib/nagios/plugins/check_justconnect_heartbeat
#    0 - all ok
#    1 - warning
#    2 - critical
#    3 - unknown 

# Check if hostname has been specified
checkArguments() {
    if [ -z "$1" ]
    then
        echo "No hostname given."
        exit 3
    fi
}


# Returns the heartbeat status list of Just Connect and its used sub-systems
# of the specified server (first parameter) as service:[OK,WARN,ERROR] status
# $1 - the host name
getHeartbeatByServer() {

    hostname=$1
#    list=$(curl -skL --connect-timeout 10 http://$hostname/toro/rest/heartbeat)
    port=80
    if nc -z -w 1 $hostname $port ; then
        list=$(curl -skL --connect-timeout 8 http://$hostname/toro/rest/heartbeat)
    else
	port=1080
        list=$(curl -skL --connect-timeout 8 https://$hostname:$port/toro/rest/heartbeat)
    fi
    result=$?
    if [ $result -ne 0 ]; then
        if [ $result -eq 22 ]; then
           echo "Heartbeat request not found on $hostname."
           exit 2
        else 
           echo "Heartbeat on $hostname:$port failed with result $result."
           exit 2
        fi           
    else 
        echo "$list" | tr -d "\r" | while read line; do
            service=$(echo $line | cut -d ':' -f 1)
            status=$(echo $line | cut -d ':' -f 2)

            if [ "$status" != "OK" ]; then
                echo "Heartbeat of $service shows $status."
                exit 2
            fi
        done
	lres=$?
	[[ $lres != 0 ]] && exit $lres
          
    fi
    #everything is ok
    echo "All Status checks show OK"
    exit 0;    
}

args=$*
checkArguments $args
getHeartbeatByServer $args
