#!/bin/sh

#set -x

#------------------------------------------------------
#
#  Syntax :
#
#  cmt_make_shlib_common.sh extract-arg tag library extra-args
#
#   with :
#
#      extract-arg  : either "extract" or "no_extract"
#      tag          : the current tag(s)
#      library      : the name of the library
#      extra-args   : extra link options
#
#------------------------------------------------------

extract=$1
shift

tag=$1
shift

lib=$1
shift

extra=$*

if [ "${CMTDEBUG:-}" ]; then
unset CMTDEBUG
set -x
fi

ld=`${CMTROOT}/mgr/cmt show macro_value shlibbuilder -tag=${tag}` || exit
ldflags=`${CMTROOT}/mgr/cmt show macro_value shlibflags -tag=${tag}` || exit
suffix=`${CMTROOT}/mgr/cmt show macro_value shlibsuffix -tag=${tag}` || exit
libprefix=`${CMTROOT}/mgr/cmt show macro_value library_prefix -tag=${tag}` || exit
libsuffix=`${CMTROOT}/mgr/cmt show macro_value library_suffix -tag=${tag}` || exit

libname=${libprefix}${lib}${libsuffix}

if test "${ld}" = "" ; then
  exit 1
fi

if test "${bin}" = "" ; then
  bin=`${CMTROOT}/mgr/cmt show macro_value bin -tag=${tag}` || exit
fi

here=`/bin/pwd`
cd ${bin} || exit

/bin/rm -f ${libname}.${suffix} || exit

result=0

temp_shlib=${lib}temp_shlib

if test ${extract} = "extract"; then
  trap '/bin/rm -rf ${temp_shlib}; cd ${here}; exit ${result}' 1 2 15

  mkdir -p ${temp_shlib}
  /bin/rm -f ${temp_shlib}/*

  (cd ${temp_shlib}; ar x ../${libname}.a)
  result=$?
  if [ ${result} -ne 0 ]; then
      \rm -rf ${temp_shlib}
      cd ${here}
      exit ${result}
  fi

  #
  # Build a protected list of modules just extracted from
  # the static library
  #  Files containing space characters are accepted
  #
  test -z "$GREP_OPTIONS" || GREP_OPTIONS=
  modules=`ls -1 ${temp_shlib} | \
           grep '[.]o$' | \
           sed -e 's#^#'${temp_shlib}'/#' \
               -e 's#^#"#g' \
               -e 's#$#"#'`

  if test "${QUIET}" = ""; then set -v; fi

  eval ${ld} ${ldflags} -o ${libname}.${suffix} ${modules} ${extra}
  result=$?

  if test "${QUIET}" = ""; then set +v; fi

  /bin/rm -rf ${temp_shlib}

else

  if test "${QUIET}" = ""; then set -v; fi

  eval ${ld} ${ldflags} -all ${libname}.a -o ${libname}.${suffix} ${extra} -rpath `/bin/pwd`
  result=$?

  if test "${QUIET}" = ""; then set +v; fi

fi

cd ${here}
exit ${result}
