#!/bin/bash

# Report histogram of inobt record freecounts

die() {
	echo "$@" >> /dev/stderr
	exit 1
}

dev="$1"
test -b "${dev}" || die "${dev}: not a block device"

agcount="$(xfs_info "${dev}" | grep agcount= | sed -e 's/^.*agcount=\([0-9]*\).*$/\1/g')"
sparse=
xfs_info "${dev}" | grep -q sparse=1 && sparse=yes

rm -f /tmp/barf
seq 0 "$(( agcount - 1 ))" | while read ag; do
	xfs_db -f -c "agi ${ag}" -c "addr root" -c "btdump" "${dev}"
done > /tmp/barf

col=2
test -n "${sparse}" && col=4
grep : /tmp/barf | awk -F ',' "{print \$${col}}" | sort | uniq -c | sort -g -k 1 | awk '{print $0; if ($2 == 0) zerofree_nr = $1; freecount_total += ($1 * $2); total += $1;}END{printf("%d inobt recs; zero free %.2f%% of recs; avg freecount %.2f\n", total, zerofree_nr * 100.0 / total, freecount_total / total);}'
