#!/bin/sh

# If using normal root, avoid changing anything.
if [ -z "$RPM_BUILD_ROOT" ] || [ "$RPM_BUILD_ROOT" = "/" ]; then
	exit 0
fi

STRIP=${1:-strip}
NCPUS=${RPM_BUILD_NCPUS:-1}

# 32 was chosen as a compromise between reducing the overhead of starting new
# processes and distributing the work load evenly over as much processors as
# possible
MAX_ARGS=32

case `uname -a` in
Darwin*) exit 0 ;;
*) ;;
esac

# Below is the explanation of commands in the order of their appearance
# Ignore /usr/lib/debug entries
# Ignore all ruby, python, and js source files
# Ignore all go(guile objects & golang) files
# Consider files with only single link
# Run the file command to find relevant non-stripped binaries, with bundle size of 32
# Ignore all 'no machine' files
# Only operate on non-stripped binaries

# $2 is 1 when __debug_package is defined (find-debuginfo will run and do a
# full strip), 0 otherwise. When debuginfo is disabled, brp-strip is the only
# stripping step, so use --strip-unneeded to also remove .symtab/.strtab.
# When debuginfo is enabled, keep -g so .symtab remains available for tools
# like perf without the debuginfo package installed.
DEBUGINFO_ENABLED=${2:-0}
if [ "$DEBUGINFO_ENABLED" = "1" ]; then
  STRIP_FLAGS="-g"
else
  STRIP_FLAGS="--strip-unneeded"
fi

strip_elf_binaries()
{
  local nlinks="${1}"
  local nprocs="${2}"

  cd "$RPM_BUILD_ROOT" || return 0
  find . -type f \
    ! -regex '\./usr/lib/debug.*' \
    ! -name "*.py" ! -name "*.js" ! -name "*.rb" \
    ! -name "*.go" -links "${nlinks}" -print0 | \
    xargs -0 -r -P${nprocs} -n${MAX_ARGS} sh -c "file \"\$@\" | \
    sed -n -e 's/^\(.*\):[ 	]*ELF.*, not stripped.*/\1/p' | \
    grep -v 'no machine' | \
    xargs -I\{\} $STRIP $STRIP_FLAGS \{\}" ARG0
}

# strip all binaries with single link
strip_elf_binaries "1" "${NCPUS}"

# strip all binaries with more than 1 link
strip_elf_binaries "+1" "1"
