#!/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:v" opt; do
  case "$opt" in
    d)
      D="$OPTARG"
      ;;
    v)
      djstubify -v
      exit $?
      ;;
    \?)
      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
  OFFS=`LC_ALL=C readelf -S $TMP | grep .gnu_debuglink | \
    tr -s '[:space:]' | cut -d " " -f 6 | sed -E -e 's/0*/0x/'`
  SO=$TMP
  DOPT="-n $OFFS -l $DBG"
fi

ID="`LC_ALL=C readelf -S $SO | grep .dj64startup`"
if [ -n "$ID" ]; then
  SZ=`LC_ALL=C readelf -S $SO | grep -A 1 .dj64startup | tail -n 1 | \
    tr -s '[:space:]' | cut -d " " -f 2 | sed -E -e 's/0*/0x/'`
  OFF=`echo "$ID" | tr -s '[:space:]' | cut -d " " -f 6 | sed -E -e 's/0*/0x/'`
  DOPT="$DOPT -S $SZ -O $OFF -f 0x8000"
fi

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

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