#!/usr/bin/bash -e

export PLUGIN_ARGS="$@"

if [ -x /usr/bin/valkey-cli ]; then
  CLICMD=/usr/bin/valkey-cli
elif [ -x /usr/bin/keydb-cli ]; then
  CLICMD=/usr/bin/keydb-cli
elif [ -x /usr/bin/redis-cli ]; then
  CLICMD=/usr/bin/redis-cli
else
  echo "valkey CRITICAL - missing command valkey-cli"
  exit 1
fi

$CLICMD $PLUGIN_ARGS --raw info 2>&1 | tr -d '\r' | gawk -F: '
  function get(key, unit) {
    value = v[key]
    if (value=="") return ""
    return sprintf("%s=%s%s", key, value, unit)
  }
  BEGIN {
    error = "running"
    ret = 0
  }
  /^[a-zA-Z0-9_]+:/ {
    #gsub("\r", "", $2) # Fix CRLF generated strings.
    v[$1] = $2
    next
  }
  /^#/ { next }
  /^$/ { next }
  {
    error = $0
    ret = 2
  }
  END {
    reply = sprintf("|%s %s %s %s %s %s %s", \
      get("connected_clients", ""), \
      get("used_memory", "B"), \
      get("used_memory_rss", "B"), \
      get("used_memory_peak", "B"), \
      get("maxmemory", "B"), \
      get("total_connections_received", "c"), \
      get("total_commands_processed", "c") \
    )
    if (ret==2) {
      print "valkey CRITICAL - " error reply
    } else if (ret==1) {
      print "valkey WARNING - " error reply
    } else {
      print "valkey OK - " error reply
    }
    exit ret
  }
'
