#! /bin/sh -f

args=''
outfile=''
ofiles=''
libdirs=''
nolibs='n'

die () {
  echo "$1" >&2
  exit 1
}

for arg in ` echo "$LIBRARY_PATH" | tr : ' ' `
do
  libdirs="$libdirs '-L$arg'"
done

while [ $# -gt 0 ]
do
  case "$1" in
  -o)
    shift
    test $# -gt 0 || die "missing arg for -o"
    outfile="$1"
    ;;
  *.o | *.o0)
    ofiles="$ofiles '$1'"
    args="$args '$1'"
    ;;
  -L*)
    libdirs="$libdirs '$1'"
    ;;
  -nolibs)
    nolibs='y'
    ;;
  -l*)
    test "$nolibs" = n && args="$args '$1'"
    ;;
  *)
    args="$args '$1'"
    ;;
  esac
  shift
done

test "X$ofiles"  != X || die "no input files"
test "X$outfile" != X || die "no output file"

outfile=` echo "$outfile" | sed -e 's/\.o$//' `

# Expect: outfile=<libname><version>
# Note: this is the old mico library format; mico-shld still expects this
# because it is an exported script that users might depend on
hasv=` echo "$outfile" | sed -e 's/\([^0-9]\+\)\([\.0-9]\+\)//' `
if test "x$hasv" = "x"; then
 libname=` echo "$outfile" | sed -e 's/\([^0-9]\+\)\([\.0-9]\+\)/\1/' `
 version=` echo "$outfile" | sed -e 's/\([^0-9]\+\)\([\.0-9]\+\)/\2/' `
 somajor=` echo "$version" | sed -e 's/\([0-9]\+\)\.\([0-9]\+\).*/\1.\2/' `
else
 libname="$outfile"
 version="1.0.0"
 somajor="1"
fi

# Prep variables
outfile="$libname.so.$version"
soname="$libname.so.$somajor"

# This is how GNU ld does it, there should be a switch here for whatever
# other linkers mico supports
soflags="-Wl,-soname=$soname"

ldcmd="c++ -shared $soflags -fPIC -fPIC -rdynamic $libdirs -L/usr/share/qt3/lib  -o $outfile \
 $args" # -lreadline -lncurses -lssl -lcrypto -ldl -lm 

echo "$ldcmd"
eval "$ldcmd" || exit

# Careful, soname or libname could equal the outfile
test -f $soname          || ln -f -s $outfile $soname
test -f $libname.so || ln -f -s $outfile $libname.so

# for HP-UX
chmod 555 "$outfile"
