#!/bin/bash

if [ -z "$1" ]; then
  echo "A ldiskfs device must be specified, 'md0' for example." >&2
  exit
elif [ ! -d /proc/fs/ldiskfs/$1 ]; then
  echo "Path not found: /proc/fs/ldiskfs/$1" >&2
  exit
fi
dev=$1

# Decay factor controls how fast to reduce the impact that bfree values for
# subsequent groups have on the "weighted" bfree value for the current group.
# Valid values are 1..100, with 100 meaning only the current group bfree matters,
# and 1 results in picking a group number that is followed by mostly empty groups.
decay=20

current=$(cat /proc/fs/ldiskfs/${dev}/mb_last_group)
tmpfile=$(mktemp)
startgrp=$(( current + 100 - decay ))
previous=0

# Read mb_groups info in reverse, starting from a bit above the current mb_last_group
while read group bfree therest; do
  weighted=$(( ( previous * ( 100 - decay ) +  bfree * decay ) / 100 ))
  echo $group $weighted >> $tmpfile
  previous=$weighted
done < <(head -n $startgrp /proc/fs/ldiskfs/${dev}/mb_groups | tr -d '#:' | grep -v group | tac)

# Break a tie by picking the lower group number
sort -k2nr -k1,1n $tmpfile | head -n 1 | awk '{print $1}'

#echo $tmpfile
rm -f $tmpfile
