#!/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=$*

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

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}`
fi

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

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

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)

  #
  # 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}
