#!/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

# shellcheck disable=SC2046
for file in $(file $(find "$tarball" -type f)|grep  ' ELF '|sed -e s/:.*//|grep -v '\.o$'|grep -v exit_37|grep -v pelican); 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
