#!/bin/bash
ITYPE=$1
IPORT=$2
HOSTNAME=$3

if [ "$ITYPE" = "rtyserver" ]
then
    port=$(( $IPORT + 3 ))

    must_be_alive_answer=`curl http://$HOSTNAME:$port/?command=get_must_be_alive 2>/dev/null`
    echo "$must_be_alive_answer" | grep -q '"must_be_alive"[ ]*:'
    if [ $? -eq 0 ]
    then
        echo "$must_be_alive_answer" | grep '"must_be_alive"[ ]*:' | cut -d: -f 2 | grep -o -q true
        [ $? -ne 0 ] && exit 0
    fi

    status=`curl http://$HOSTNAME:$port/status 2>/dev/null`

    [ -z "$status" ] && exit 1

    echo "$status" | grep 'Search_Server_Running[ ]*:' | cut -d: -f 2 | grep -o -q 1;
    search_server_running=$?

    echo "$status" | grep 'Active[ ]*:' | cut -d: -f 2 | grep -o -q 1;
    active=$?

    [ $search_server_running -eq 0 ] && [ $active -eq 0 ] && exit 0

    exit 1
else
    if [ "$ITYPE" = "searchproxy" ]
    then
        nc -vz `hostname` $IPORT > /dev/null 2>&1
        port_open=$?
        [ $port_open -ne 0 ] && exit 1
        port=$(( $IPORT + 3 ))
        status=`curl http://$HOSTNAME:$port/status 2>/dev/null`
        [ -z "$status" ] && exit 1
        echo "$status" | grep -o -q 'Started';
        has_started=$?
        [ $has_started -eq 0 ] && exit 0
        echo "$status" | grep 'IsServerDataStatus_OK[ ]*:' | cut -d: -f 2 | grep -o -q 1;
        is_ok=$?
        [ $is_ok -eq 0 ] && exit 0
        exit 1
    else
        nc -vz `hostname` $IPORT > /dev/null 2>&1
    fi
fi
