#!/bin/bash
#
# Adjusts reserved blocks on the root filesystem to 2% using tune2fs.
#
# This is run as a pkg_postinst script, so always exit with code 0.
#

TARGET_PCT=2

# Find the root block device.
root_devno=$(mountpoint -d /)
dev_name=$(basename "$(readlink -f /sys/dev/block/"$root_devno" 2>/dev/null)" 2>/dev/null)
root_dev="/dev/$dev_name"

if [ -z "$dev_name" ] || [ ! -b "$root_dev" ]; then
    echo "root filesystem is not on a local block device, skipping reserved blocks adjustment"
    exit 0
fi

tune2fs_output=$(tune2fs -l "$root_dev" 2>&1)
if [ $? -ne 0 ]; then
    echo "failed to inspect root filesystem with tune2fs, skipping reserved blocks adjustment: $tune2fs_output"
    exit 0
fi

block_count=$(echo "$tune2fs_output" | awk '/^Block count:/ {print $NF}')
reserved_count=$(echo "$tune2fs_output" | awk '/^Reserved block count:/ {print $NF}')

if [ -z "$block_count" ] || [ -z "$reserved_count" ] || [ "$block_count" -eq 0 ]; then
    echo "warning: could not parse block counts from tune2fs output, skipping reserved blocks adjustment"
    exit 0
fi

target_blocks=$((block_count * TARGET_PCT / 100))

if [ "$reserved_count" -le "$target_blocks" ]; then
    echo "root filesystem reserved blocks already at or below ${target_blocks} blocks, skipping"
    exit 0
fi

echo "adjusting reserved blocks to ${TARGET_PCT}%"
tune2fs -m "$TARGET_PCT" "$root_dev"
if [ $? -ne 0 ]; then
    echo "failed to adjust root filesystem reserved blocks with tune2fs"
    exit 0
fi
