#!/bin/bash
##
## RHEL binutils ld(1) wrapper to do chrpath(1) hacks
## Copyright (c) 2016 SATOH Fumiyasu @ OSS Technology Corp.
##               <http://www.OSSTech.co.jp/>
##
## License: GNU General Public License version 3 or later
##

set -u

ld_cmd="${LDWRAPPER_LD:-/usr/bin/ld}"
chrpath_cmd="${LDWRAPPER_CHRPATH:-/usr/bin/chrpath}"
output="a.out"

args=("$@")
for ((i=0; i < $#; i++)); do
  arg="${args[$i]}"
  case "$arg" in
  -o?*)
    output="${arg#-o}"
    ;;
  -o)
    if [[ $i+1 -lt $# ]]; then
      output="${args[$i+1]}"
    fi
    ;;
  --output=*)
    output="${arg#--output=}"
    ;;
  esac
done

"$ld_cmd" "$@" || exit $?

if "$chrpath_cmd" --list "$output" 2>/dev/null |grep ': RPATH=' >/dev/null; then
  "$chrpath_cmd" --convert "$output"
  chrpath_status=$?
  if [[ $chrpath_status -ne 0 ]]; then
    echo "$0: ERROR: $chrpath_cmd failed" 1>&2
    rm -f "$output"
    exit $chrpath_status
  fi
fi

exit 0

