#!/bin/bash
#
# Fetch an OCA instance metric from the billingsnapshot table
#

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

INSTANCE=$1
METRIC=$2

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

# Convert to HEX to prevent any injection
xINSTANCE=$(echo -n "$INSTANCE" | xxd -c256 -l256 -p)
xMETRIC=$(echo -n "$METRIC" | xxd -c256 -l256 -p)

RES=$(mysql -NB -e "
SELECT d.Value
  FROM ocacommon.zabbixmetric c
   JOIN ocacommon.zabbixmetriclog l ON l.SnapshotDate > CURDATE()-INTERVAL 1 DAY AND l.AccountCode = UNHEX('$xINSTANCE')
   JOIN ocacommon.zabbixmetriclogdatapoint d ON d.MetricID = c.id AND d.ZabbixMetricLogID = l.id
  WHERE c.Metric = UNHEX('$xMETRIC')
ORDER BY l.SnapshotDate DESC LIMIT 1
" 2>/dev/null)

# shellcheck disable=SC2181
if [ $? -ne 0 ]; then

  #fallback to the old behaviour
  RES=$(mysql -NB -e "
  SELECT \`$METRIC\`
    FROM ocacommon.billingsnapshot
   WHERE AccountCode = UNHEX('$xINSTANCE')
         AND SnapshotDate > CURDATE()-INTERVAL 1 DAY
  ORDER BY SnapshotDate DESC LIMIT 1
  ")

  # shellcheck disable=SC2181
  if [ $? -ne 0 ]; then
  	# Invalid metric (probably...)
  	echo "Unknown metric '$METRIC'" >&2
  	echo -n "ZBX_UNSUPPORTED"
  	exit 4
  elif [ -z "$RES" ]; then
    # Invalid instance
    echo "Unknown instance '$INSTANCE' or metric '$METRIC'" >&2
    echo -n "ZBX_UNSUPPORTED"
    exit 5
  fi

  echo "$RES"
  exit

elif [ -z "$RES" ]; then
  # Invalid instance
  echo "Unknown instance '$INSTANCE' or metric '$METRIC'" >&2
  echo -n "ZBX_UNSUPPORTED"
  exit 5
fi

echo "$RES"
