#!/bin/bash
#
# Search $1 path (default to /) for files with over $2 (defaults to 100) fragments and attempts to defragment them.
#
# Author: Kyle Manna
#
root=${1:-/}
min=${2:-100}
find $root -xdev -type f -print0 | xargs -0 filefrag | sed -e "s/^\(.*\): \(.*\) extents found/\2 \1/" | awk "{ if (\$1 > $min) print \$0; }" | while read line; do
file=${line#* }
before=${line%% *}
btrfs filesystem defrag "$file"
after=$(filefrag "$file" | sed -e "s/^\(.*\): \([0-9]\+\) extents\? found/\2/")
echo "$file: $before -> $after"
done