#!/bin/bash
# If using normal root, avoid changing anything.
if [ -z "$RPM_BUILD_ROOT" -o "$RPM_BUILD_ROOT" = "/" ]; then
	echo "RPM_BUILD_ROOT is not set or set to / : skipping strip"
	exit 0
fi
if [ "$NO_BRP_STRIP_DEBUG" = "true" ] ; then
	echo "NO_BRP_STRIP_DEBUG is set: skipping strip"
	exit 0
fi

FIND_IGNORE=(
    '('
    -path "$RPM_BUILD_ROOT/usr/lib/debug" -o -path
    "$RPM_BUILD_ROOT/lib/modules" -o -path "$RPM_BUILD_ROOT/opt/cross" -o
    -path "$RPM_BUILD_ROOT/proc"
    ')'
    -prune -o
)

# Strip debuginfo from ELF binaries, but not static libraries or kernel modules
find "$RPM_BUILD_ROOT" "${FIND_IGNORE[@]}" \( -name "*.a" -o -name "*.ko" \) \
   -prune -o \
   -type f \( -perm /0111 -o -name "*.so*" \) \
   -exec file {} + | \
sed -n -e 's/^\(.*\):[ ]*ELF.*, not stripped.*$/\1/p' |  while read f; do
	mode="$(stat -c %a "$f")"
	chmod u+w "$f" || :
	${CROSS_COMPILE}strip -p --strip-debug --discard-locals -R .comment -R .note "$f" || :
	chmod "$mode" "$f"
done

# Don't strip debuginfo from static libs, but compiler-generated local symbols
find "$RPM_BUILD_ROOT" "${FIND_IGNORE[@]}" -type f -name "*.[ao]" -print | while read f; do
	case $(file "$f") in
	    *"current ar"*|*ELF*", not stripped"*)
		chmod u+w "$f" || :
		${CROSS_COMPILE}strip -p --discard-locals -R .comment -R .note -R .gnu.lto_* -R .gnu.debuglto_* -R __patchable_function_entries -N __gnu_lto_v1 "$f" || :
		;;
	    *)
		echo "WARNING: Strange looking archive $(file $f)"
		continue
		;;
	esac
done
