#!/bin/bash
#
# Fetch an OCA instance's status on the current node
#

if [ $# -ne 1 ]; then
        echo "Usage: $0 [oca_]<instance>"
        exit 1
fi

INSTANCE=$1

# Strip an (optional) leading oca_ from the instance name
INSTANCE=${INSTANCE#oca_}

if [[ ! "$INSTANCE" =~ ^[-_A-Za-z0-9]+$ ]]; then
        echo "Illegal instance name '$INSTANCE'" >&2
        echo -n "ZBX_UNSUPPORTED"
        exit 2;
fi

# Check that there is at least a user for the instance
if ! id -u "oca_${INSTANCE}" >/dev/null 2>/dev/null; then
        echo "No such instance (user account oca_${INSTANCE} not found)" 2>&1
        echo 'ZBX_UNSUPPORTED'
        exit 3
fi

# Ask the instance to report it's status, collecting any stdout or stderr content
OUTPUT=$(sudo -n -u oca "/home/oca/accounts/${INSTANCE}/code/ngsys/bin/is-online.php" 2>&1)
# Grab the exit code
RC=$?

# We use the following mapping:
#   0 => offline
#   1 => online
#   2 => unknown / error
#
# So that checks can safely do a >= 1 for we don't *know* for sure it's offline
#

if [[ -n "${OUTPUT}" || $RC -ge 2 ]]; then
    # If there was any output or the exit code was 2 or higher assume the data is bad, because it will usually be an error
    echo -n '2'
elif [[ $RC -eq 0 ]]; then
    # If there was no output AND the exit code was zero, then the instance is online
    echo -n '1'
elif [[ $RC -eq 1 ]]; then
    # If there was no output AND the exit code was one, then the instance is offline
    echo -n '0'
else
    # We have NFI what happened and weren't expecting it, return the error state (2)
    echo -n '2'
fi

