#!/usr/bin/env bash
# memory_check.sh — RAM usage percentage.
set -euo pipefail

TOTAL=1
AVAIL=1

if [ -r /proc/meminfo ]; then
  TOTAL=$(awk '/^MemTotal:/ {printf "%d", $2}' /proc/meminfo)
  AVAIL=$(awk '/^MemAvailable:/ {printf "%d", $2}' /proc/meminfo)
elif [ "$(uname)" = "Darwin" ]; then
  MEM=$(vm_stat 2>/dev/null | awk '
    /page size/ {ps=$8}
    /Pages free/   {free+=$NF}
    /Pages active/ {active+=$NF}
    /Pages wired/  {wired+=$NF}
    END {printf "%.2f %.2f", ps*(free+active+wired)/1048576, ps*wired/1048576}')
  TOTAL=$(echo "$MEM" | awk '{printf "%.0f", $1}')
  AVAIL=$(echo "$MEM" | awk '{printf "%.0f", $1 - $2}')
fi

if [ "$TOTAL" -eq 0 ]; then TOTAL=1; fi
if [ "$AVAIL" -lt 0 ]; then AVAIL=0; fi

USED_PCT=$(awk "BEGIN {printf \"%.1f\", (1 - $AVAIL/$TOTAL)*100}")

echo "{\"health\":\"healthy\",\"metrics\":{\"mem_pct\":$USED_PCT}}"
