#!/bin/sh
#
# This is a wrapper script which is used when buliding a shared 
# library file of language bindings.
# This script was originally implemented by Moriyoshi Koizumi.
#

libdir=@prefix@/lib

progname=`basename "$0"`

dllibext=
out_dir=
out_file=
out_filename=
cygout_filename=
args=

TAG=CXX

if test -z "$1"; then
    echo "${progname}: linker executable must be specified." >&2
    exit
fi

linker_tmpdir=`mktemp -d $PWD/XXXXXXXX`
stage_dir="${linker_tmpdir}/stage"

LD="$1"
shift

while test -n "$1"; do
    case "$1" in
        --tag=*)
            TAG=`echo "$1" | sed -e 's/^--tag=//'`
            ;;
        -o)
            shift
            out_file="$1"
            dllibext=`echo "${out_file}" | sed -e 's/.*\(\.[^.]*\)$/\1/'`
            out_dir=`dirname "${out_file}"`
            out_filename=`basename "${out_file}" "${dllibext}"`
            cygout_filename=`echo ${out_filename} | sed 's/lib/cyg/'`
            ;;
        *.o)
            lt_obj=`echo "$1" | sed -e 's/\.o$/.lo/'`
            args="${args} \"${lt_obj}\""
            ;;
        --libdir)
            shift
            libdir="$1" 
            ;;
        lib*.la | */lib*.la)
            mkdir -p "${stage_dir}/${libdir}" && \
                eval "@abs_top_srcdir@/libtool --mode=install cp \"$1\" \"${stage_dir}/${libdir}\""
            libname=`basename "$1" | sed -e 's/lib\([^.]*\)\.la/\1/'`
            args="${args} \"$1\""
            ;; 
        *)
            args="${args} \"$1\""
            ;;
    esac
    shift
done

mkdir -p "${stage_dir}/${libdir}"

if test -z "$out_file"; then
    echo "${progname}: -o option not specified." >&2
    rm -rf "${linker_tmpdir}"
    exit 1
fi

eval "@abs_top_srcdir@/libtool --tag=\"$TAG\" --mode=link \"$LD\" -rpath \"${libdir}\" -inst-prefix-dir \"${stage_dir}\" -module -avoid-version -export-dynamic -shrext "${dllibext}" -o \"${out_dir}/${out_filename}.la\" $args" && \
    eval "@abs_top_srcdir@/libtool --mode=install cp \"${out_dir}/${out_filename}.la\" \"${stage_dir}/${libdir}/${out_filename}.la\"" 

  if [ -e "${stage_dir}${libdir}/${out_filename}${dllibext}" ]; then
    cp "${stage_dir}${libdir}/${out_filename}${dllibext}" "${out_dir}"
  fi

  # for cygwin
  if [ -e "${stage_dir}${libdir}/${cygout_filename}${dllibext}" ]; then
    cp "${stage_dir}${libdir}/${cygout_filename}${dllibext}" "${out_dir}/${out_filename}${dllibext}"
  fi

rm -rf "${linker_tmpdir}"
