#!/bin/sh
# This command sets the RPATH for all dynamically linked  executables in a tarball directory
if [ $# -ne 2 ]; then
    echo 'Error: missing argument'
    echo "Usage: $(basename "$0") tarball-directory rpath"
    exit 1
fi
tarball=$1
rpath=$2
if [ ! -d "$tarball" ]; then
    echo "Error: $tarball is not a directory"
    echo "Usage: $(basename "$0") tarball-directory rpath"
    exit 1
fi

PATCHELF='patchelf'
if [ -x /usr/bin/lief-patchelf ]; then
    PATCHELF='lief-patchelf'
fi
echo "Using $PATCHELF"

# shellcheck disable=SC2046
for file in $(file $(find "$tarball" -type f)|grep  ' ELF '|sed -e s/:.*// | egrep -v '(\.o$|exit_37|pelican|get_user_ns)'); do
    echo Set RPATH to "$rpath" in "$file"
    # --force-rpath only works when there is no pre-existing RPATH or RUNPATH
    if ! $PATCHELF --remove-rpath "$file"; then
        echo ERROR: Cannot remove RPATH from "$file"
        exit 1
    fi
    # Force patchelf to set the RPATH, not RUNPATH
    if ! $PATCHELF --force-rpath --set-rpath "$rpath" "$file"; then
        echo ERROR: Cannot set RPATH in "$file"
        exit 1
    fi
done
