#!/usr/bin/env sh
#
# ----------------------------------------------------------------------------
#
# Copyright 2022 IBM Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ----------------------------------------------------------------------------
#

set -eu

die() { echo "$*" >&2; exit 1; }

if [ $# -lt 2 ]; then
    die "Usage: $0 <object> <symbol> "
fi

obj="$1"
sym="$2"
lib="$(dirname "$0")/../lib/libchop-marks-dyn-addr-lib.so"
script="$(mktemp)"

set +e
ldd "$obj" 1> /dev/null 2> /dev/null
error=$?
set -e

if [ "$error" -ne 0 ]; then
    echo 0
    exit
fi

cleanup() {
    rm -f "$script"
}
trap cleanup EXIT

# shellcheck disable=SC2129
echo "export LD_BIND_NOW=1" > "$script"
# shellcheck disable=SC2129
echo "export LD_SYMBOL=$sym" >> "$script"
# shellcheck disable=SC2129
echo "export LD_PRELOAD=$lib" >> "$script"
# shellcheck disable=SC2129
echo "$(dirname "$obj")/$(basename "$obj")" >> "$script"
chmod +x "$script"
setarch "$(uname -m)" -R "$script"
rm -f "$script"
