#!/bin/sh
if [ "$#" -lt 1 ]; then
	echo "usage: $0 <file1> [fileN]" >&2
	exit 1
fi

maxlength=0
for x in "$@"; do
	thislength="`expr length "$x:"`"
	if [ "$thislength" -gt "$maxlength" ]; then
		maxlength=$thislength
	fi
done

for x in "$@"; do
	BMAP="`xfs_bmap -l "$x"`"

	if [ "$?" != 0 ]; then
		continue
	fi


	printf "%-${maxlength}s " "$x:"

	echo "$BMAP" | tr '.:[]' ' ' | tail -n +2 | awk '
{
	extent=$1;
	startoff=$2;
	endoff=$3;
	startblock=$4;
	endblock=$5;
	count=$6
	
	extents++;
	blocks+=count;

	if (extent == 0 || startoff != laststartoff + lastcount || startblock == "hole") {
		ideal++;
	} else {
#		print "not contiguous: "$0
	}
	
	laststartoff=startoff;
	lastcount=count;
}

END {
	if (extents != 0) {
		if (ideal != 0) {
			fragfact = (extents - ideal) * 100.0 / extents;
		} else
			fragfact = 0;

		printf("%5.2f%% fragmentation factor (%lu blocks, %lu extents, %lu ideal)\n", fragfact, blocks, extents, ideal);
	} else {
		print "no extents or error"
	}
}
'
done
