#!/usr/bin/env bash
#
# Read memory usage in FreeBSD
set -euo pipefail
IFS=$'\n\t'
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

SLEEP_INTERVAL=${SLEEP_INTERVAL:-30}

while true; do
    page_size=$(sysctl -n hw.pagesize)
    free_pages=$(sysctl -n vm.stats.vm.v_free_count)
    free_bytes=$((page_size * free_pages))
    total_pages=$(sysctl -n vm.stats.vm.v_page_count)
    free_percent=$((100 * free_pages / total_pages))
    text=""

    if [ $free_bytes -ge $((1024 * 1024 * 1024)) ]; then
        text="$((free_bytes / 1024 / 1024 / 1024)) GiB"
    fi

    tooltip="${free_percent}%"

    jq --unbuffered --compact-output <<EOF
{
"text":"${text}",
"tooltip":"${tooltip}",
"percentage":${free_percent}
}
EOF
    sleep $SLEEP_INTERVAL
done
