#!/bin/bash
############################################
# dtb-askstatus
#
# Helper script to determine the DTB lamps. It opens a TCP socket on 1400 and returns the status from the DTB.
# Usage: ./dtb-askstatus
# 
# Copyright (c) 2017 Unify GmbH & Co. KG
# Demeter Aron, Kemenes Robert 
# aron.demeter.ext@unify.com, robert.kemenes.ext@unify.com
#
# Last modification: 26.09.2018 in dtb-1.0-44.noarch.rpm
############################################

# Import definitions
CMD=$(basename $0)
if [ -f /opt/dtb/bin/_common_definitions ]; then
    . /opt/dtb/bin/_common_definitions
else
	logger -t $CMD -p ERROR -s "The /opt/dtb/bin/_common_definitions file does not exist, exiting the script..."
	exit 1
fi

isDTBrunning=$(crm resource status rsc4k_dtb 2>&1)
if [[ $isDTBrunning == "resource rsc4k_dtb is NOT running" ]]; then
	plog "DTB resource is not running"
	exit 55
else
	plog "DTB resource is running"
fi

plog "Asking DTB status via TCP..."

# Open netcat socket to read data:
# Data format: A0S0M, where S=DTBServer status (0=red, 1=yellow, 2=green)
#							M=DTBMaster status (0=red, 1=green)
MESSAGE=$(nc 127.0.0.1 1400 -p 14001 2>&1)
HEXVAL=$(hexdump -e '"%X"' <<< "$MESSAGE")
plog "Message received: $HEXVAL"
# example values: A0201 (green - green  = both are running)
#				  A01   (red   - yellow = DTBserver is connected to OS4K, but not to DTBMaster)
#				  A     (red   - red    = both are stopped)
length=${#HEXVAL} 
if [ $length -eq 5 ]; then
	plog "Server status: ${HEXVAL:2:1} (1=yellow, 2=green)"
	plog "Master status: 1 (green)"
	exit ${HEXVAL:2:1}1
elif [ $length -eq 3 ]; then
	plog "Server status: ${HEXVAL:2:1} (1=yellow, 2=green)"
	plog "Master status: 0 (red)"
	exit ${HEXVAL:2:1}0
elif [ $length -eq 1 ]; then
	plog "Server status: 0 (red)"
	plog "Master status: 0 (red)"
	exit 0
fi

#Exit code format:
# SM where S can be 0=red, 1=yellow, 2=green
#      and M can be 0=red, 1=green

# MS format not good because on red-yellow it returns 1 instead of 01

exit 0