#!/bin/sh

if [ -z "$RPM_BUILD_ROOT" ]; then
	printf '%s\n' "No build root defined" >&2
	exit 1
fi

if [ ! -d "$RPM_BUILD_ROOT" ]; then
	printf '%s\n' "Invalid build root" >&2
	exit 1
fi

# If using the real root, avoid touching the live system.
if [ "$RPM_BUILD_ROOT" = "/" ]; then
	exit 0
fi

# Collect the existing perl directories as a properly quoted argument list
# (the positional parameters): word splitting and glob expansion can never
# turn them into unintended paths.
set --
for i in "$RPM_BUILD_ROOT/usr/lib/perl5" \
	"$RPM_BUILD_ROOT/usr/lib64/perl5" \
	"$RPM_BUILD_ROOT/usr/share/perl5"
do
	[ -d "$i" ] || continue
	set -- "$@" "$i"
done
[ $# -gt 0 ] || exit 0

find "$@" \( -name ".packlist" -o -name perllocal.pod \) -exec rm -f {} + || true

find "$@" -name "*.bs" | while IFS= read -r i; do
	if [ -s "$i" ]; then
		printf '%s\n' "non empty .bs file!"
	else
		rm -f "$i"
	fi
done

find "$@" -depth -type d -exec rmdir {} \; 2>/dev/null
