#!/usr/bin/sh
# remove rpath specified

# Every word handled below (rpath entries, file names) comes from untrusted
# input (binaries being built): disable pathname expansion so glob characters
# in rpath entries can never expand into real paths (path injection).
set -f

rpathSuffix=(
	"/home/abuild/rpmbuild/BUILD"
	"/home/lkp/rpmbuild/BUILD"
)

rpath=(
	"/usr/lib64"
	"/lib64"
	"/usr/lib"
	"/lib"
	"/usr/lib/../lib64"
)

buildroot="$1"

# Never fall back to scanning the live system: with an empty or missing
# build root "$buildroot/" would resolve to "/".
if [ -z "$buildroot" ] || [ ! -d "$buildroot" ]; then
	exit 0
fi

function rpathChange()
{
	localSrcPath="$1"
	localDstPath=""

	# Split the colon-separated rpath into single entries: split on ':'
	# only (entries may legitimately contain spaces) and never let the
	# shell perform pathname expansion on them (set -f above).
	IFS=':' read -r -a rpathArr <<< "$localSrcPath"

	for path in "${rpathArr[@]}"
	do
		localflag=0
		for suffix in "${rpathSuffix[@]}"
		do
			if printf '%s\n' "$path" | grep -F -- "$suffix" &> /dev/null; then
				localflag=1
				break
			fi
		done

		# Is the suffix path, delete
		if [ "$localflag" -eq 1 ]; then
			continue;
		fi

		#Is the standard path, delete
		if printf '%s\n' "${rpath[@]}" | grep -w -F -- "$path" &> /dev/null; then
			continue
		fi

		if [ x"$localDstPath" == x"" ]; then
			localDstPath="$path"
		else
			localDstPath="$localDstPath:$path"
		fi
	done

	printf '%s\n' "$localDstPath"
}

function removeRpathOrRunpath()
{
	localfile="$1"

	rpathInfo=$(chrpath -l "$localfile" | grep "RPATH=")
	runpathInfo=$(chrpath -l "$localfile" | grep "RUNPATH=")

	currPath=""
	realPath=""
	needCh=0
	if [ x"$rpathInfo" != x"" ]; then
		needCh=1
		currPath=$(printf '%s\n' "$rpathInfo" | awk -F "RPATH=" '{print $2}')
		realPath=$(rpathChange "$currPath")
	fi

	if [ x"$runpathInfo" != x"" ]; then
		needCh=1
		currPath=$(printf '%s\n' "$runpathInfo" | awk -F "RUNPATH=" '{print $2}')
		realPath=$(rpathChange "$currPath")
	fi

	if [ "$needCh" -eq 0 ]; then
		return 0
	fi

	if [ x"$realPath" == x"" ]; then
		chrpath -d "$localfile"
	else
		chrpath -r "$realPath" "$localfile"
	fi

	return 0
}

find "$buildroot/" -executable -type f -exec file {} ';' | grep "\<ELF\>" | awk -F ':' '{print $1}' | while IFS= read -r file
do
	if test -u "$file"; then
		continue
	fi

	if [ -w "$file" ]; then
		removeRpathOrRunpath "$file"
	fi
done

exit 0
