#!/usr/bin/env bash

if [ -z "$OBJCOPY" ]; then
  OBJCOPY=objcopy
fi
if [ -z "$STRIP" ]; then
  STRIP=strip
fi

if [ "$#" -lt 1 ]; then
  echo "Usage: djlink [-d <debug_name>] <solib_name> [<djstubify_opts>]"
  exit 0
fi
while getopts "d:" opt; do
  case "$opt" in
    d)
      D="$OPTARG"
      ;;
    \?)
      exit 1
      ;;
  esac
done
shift $(($OPTIND-1))
SO=$1
shift
if [ ! -f "$SO" ]; then
  echo "$0: file $SO missing"
  exit 1
fi

if [ -n "$D" ]; then
  if [ -z "`readelf -S $SO | grep .debug_info`" ]; then
    echo "$0: -d is specified but $SO is stripped"
    exit 1
  fi
  DBG="/tmp/$D"
  $OBJCOPY --only-keep-debug $SO $DBG
  TMP=$(mktemp)
  $STRIP -o $TMP $SO
  $OBJCOPY --add-gnu-debuglink=$DBG $TMP
  SO=$TMP
  DOPT="-l $DBG"
fi

CMD="djstubify -g $* -l $SO $DOPT"
#echo "$CMD"
$CMD

[ -z "$TMP" ] || rm "$TMP"
if [ -n "$DBG" -a -f "$DBG" ]; then
  rm $DBG
fi
