#!/bin/bash

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

ABS_HOME=$SCRIPT_DIR/../..
ABS_HOME=$(builtin cd $ABS_HOME; pwd)

# SLOT_NUMBER is the slot on which this is created
SLOT_NUMBER=$(echo "$ABS_HOME" | awk -F'/' '{print $(NF-0)}')

SNMP_PORT="5${SLOT_NUMBER}24"
MIB=1.3.6.1.4.1.227.2.1.0


TRIES=20
SLEEP_INTERVAL=30

for ((i = 1; i <= TRIES; i++)); do
    result=$(snmpwalk -v1 -c public $(hostname):${SNMP_PORT} ${MIB} | cut -d "=" -f2 | xargs)

    case "$result" in
        "INTEGER: -1")
            echo "Server is not ready yet"
            ;;
        "INTEGER: 1")
            echo "Server has started"
            exit 0
            ;;
        "INTEGER: 2")
            echo "Server is initializing..."
            ;;
        "INTEGER: 3")
            echo "Server is stopped"
            exit 1
            ;;
        *)
            echo "Try $i: Server is not ready yet. Waiting for the next check..."
            ;;
    esac
    sleep $SLEEP_INTERVAL
done

# If the loop completes without the report server starting, exit with status 1
echo "Report Server did not start after $TRIES tries. Exiting."
exit 1