Editing a .gbr file with a bash script

#!/bin/bash

# This script renames a GIMP brush (.gbr)

# Define variables
brush_file="$1"         # Input brush file
brush_name="$2"         # Current brush name
brush_new_name="$3"     # New brush name

debug=1                 # Set to 1 for debug output

echo "Renaming $brush_name to $brush_new_name"

# Check if the source brush exists
if [ ! -f "$brush_file" ]; then
  echo "Error: Source brush file not found: '$brush_file'"
  exit 1
fi

# Calculate the original header size
original_header_size=$(od -An -N 4 -tu4 --endian=big "$brush_file" | tr -d '[:space:]')

# Calculate the original name size
original_name_size=$(echo -n "$brush_name" | wc -c)

# Calculate the new name size
new_name_size=$(echo -n "$brush_new_name" | wc -c)

# Perform arithmetic operation: Subtract original name size from header size
header_minus_name=$(( original_header_size - original_name_size ))
header_plus_new_name=$(( header_minus_name + new_name_size ))

# Replace the first 4 bytes in the destination file with the new header size
printf '%08x\n' "$header_plus_new_name" | xxd -r -p | dd conv=notrunc of="$brush_file" bs=1 seek=0 count=4 > /dev/null

# Verify the replacement by checking the new header size in the destination file
verified_header_size=$(od -An -N 4 -tu4 --endian=big "$brush_file" | tr -d '[:space:]')

if [ $debug -eq 1 ]; then
  echo "Original Header size   $original_header_size"
  echo "Original Name size     $original_name_size"
  echo "Header minus name size $header_minus_name"
  echo "New Name size          $new_name_size"
  echo "New Header size        $header_plus_new_name"
  echo "Verified Header size   $verified_header_size"
fi

# Replace brush name in the renamed file
sed -i "s/$brush_name/$brush_new_name/g" "$brush_file"