[Gentoo] Cleaning up “empty” font directories

Lots of programs (mkfontscale, mkfontdir, fc-cache, etc) keep metadata information in the same directory as the fonts. That information is regenerated upon installation of any new font or removal of any existing font in that directory by the ebuild, which then changes the MD5 sums and modification times of all that metadata. This means portage won’t automatically unmerge it, so we need to create a function to do so.

This function, called cleanup_fonts(), checks for a font directory with only metadata files in it. If it discovers any, it deletes them. I’d appreciate a couple more eyes on the code to make sure it’s sane, because it’s already in x-modular.eclass.

You can assume FONT_DIR is already set and sane at this point. It contains the names of each subdirectory in /usr/share/fonts/ that this particular package installed into.

Sorry about the lack of indentation; it doesn’t work by default, and I couldn’t figure it out in less than 10 seconds.

cleanup_fonts() {
local ALLOWED_FILES="encodings.dir fonts.cache-1 fonts.dir fonts.scale"
for DIR in ${FONT_DIR}; do
unset KEEP_FONTDIR
REAL_DIR=${ROOT}usr/share/fonts/${DIR}

ebegin "Checking ${REAL_DIR} for useless files"
pushd ${REAL_DIR} &> /dev/null
for FILE in *; do
unset MATCH
for ALLOWED_FILE in ${ALLOWED_FILES}; do
if [[ ${FILE} = ${ALLOWED_FILE} ]]; then
# If it's allowed, then move on to the next file
MATCH="yes"
break
fi
done
# If we found a match in allowed files, move on to the next file
if [[ -n ${MATCH} ]]; then
continue
fi
# If we get this far, there wasn't a match in the allowed files
KEEP_FONTDIR="yes"
# We don't need to check more files if we're already keeping it
break
done
popd &> /dev/null
# If there are no files worth keeping, then get rid of the dir
if [[ -z "${KEEP_FONTDIR}" ]]; then
rm -rf ${REAL_DIR}
fi
eend 0
done
}