#!/bin/bash -e

# Work around problems with libtool putting PIC objects in convenience libraries in 
# projects with subdirectories.  The calls to 'ar' are intercepted and we create fully
# static versions alongside the sub-project archives.  ro-install understands that it
# might need to look for fully static versions instead, and will also check that
# installed archives really do not contain any PIC objects.

params=$@
orig=/opt/netsurf/arm-unknown-riscos/cross/bin/arm-unknown-riscos-ar

#echo Wrapper: $@ | tr ' ' '\n'
#echo

if [ "$1" == "x" ] && grep -q "\.libs/lib.*\.a\$" <<< $2 ; then
  echo "Detected libtool convenience library extraction - extracting static object version also"

  dir=$(sed "s#\.lax/#.lax-static/#" <<< $PWD)
  mkdir -p $dir
  pushd . >/dev/null
  cd $dir

  $orig x $(sed "s#\.a\$#.a-static#" <<< $2)
  popd >/dev/null

elif [ "$1" == "cru" ] && [ "${2:0:5}" == ".libs" ] ; then
  echo "Detected libtool convenience library creation - creating static object version also"

  params=$(sed -r -e "s#\.libs/([a-zA-Z0-9_-]+\.o)#\1#g" -e "s#\.lax/#.lax-static/#g" <<< ${@:3})

  # libtool likes to rename things sometimes to avoid archive name conflicts.  Just hope it's static.
  for param in $params; do
    if ! [ -e $param ] ; then
      mkdir -p $(dirname $param)
      cp -av $(sed s#-static## <<<$param) $param
    fi
  done

  $orig cru ${2}-static $params
fi

$orig $@
