#! /bin/sh
# Generate GNUmakefile.link for TOM makefiles
# Written by Pieter J. Schoenmakers <tiggr@gerbil.org>
# 
# Copyright (C) 1998 Pieter J. Schoenmakers.
# 
# This file is part of TOM.  TOM is distributed under the terms of the
# TOM License, a copy of which can be found in the TOM distribution; see
# the file LICENSE.
#
# $Id: genlinkfile,v 1.9 1998/03/17 17:46:22 tiggr Exp $

outfile=
gendir=${GENDIR}
suffix=
dirs=

usage () {
  echo usage: $0 '[-o outfile] [-I incdir]* [-s suffix] unit ...' >&2
  exit 2
}

while test $# -ne 0; do
  case $1 in
    -I) shift
	dirs="$dirs $1"
	shift || usage
	;;

    -o) shift
	outfile=$1
	shift || usage
	;;

    -s)	shift
	suffix=$1
	shift || usage
	;;

    -)	shift
	break
	;;

    -*)	usage
	;;

    *)
	break
	;;
  esac
done

if test x${outfile} = x; then
  exec 3>&1
else
  test -f ${outfile} && mv ${outfile} ${outfile}~
  exec 3> ${outfile}
fi

for unit in $*; do
  unit_dir=
  for dir in $dirs; do
    for udir in ${dir} ${dir}/${unit}; do
      if test '(' -f ${udir}/${unit}.u ')'; then
	unit_dir=${udir}
	break
      fi
    done
    if test x${unit_dir} != x; then break; fi
  done

  if test x${unit_dir} = x; then
    echo unable to locate unit ${unit}
  else
    echo using unit ${unit} from ${unit_dir} >&2
  fi

  if test -f ${unit_dir}/lib${unit}${suffix}.la; then
    echo UNIT_OBJS+=${unit_dir}/lib${unit}${suffix}.la >&3
    echo UNIT_DEPS+=${unit_dir}/lib${unit}${suffix}.la >&3
  else
    case "${unit_dir}" in
      /*);;
      *) unit_dir=`pwd`/${unit_dir};;
    esac
    if test `expr "${ld_lib_dirs}" : ".*${unit_dir}"` -eq 0; then
      ld_lib_dirs="${ld_lib_dirs} ${unit_dir}"
      echo UNIT_OBJS+=-L${unit_dir} >& 3
      if test -f ${unit_dir}/lib${unit}${suffix}.a; then
	echo UNIT_DEPS+=${unit_dir}/lib${unit}${suffix}.a >& 3
      fi
    fi
    echo UNIT_OBJS+=-l${unit}${suffix} >&3
  fi

  if test -f ${unit_dir}/GNUmakefile.unit; then
    echo include ${unit_dir}/GNUmakefile.unit >&3
  fi
done

found=
trt_o=libtrt${suffix}.la
for dir in $dirs; do
  if test -f ${dir}/${trt_o}; then
    echo UNIT_OBJS+=${dir}/${trt_o} >&3
    echo UNIT_DEPS+=${dir}/${trt_o} >&3
    echo using trt from ${dir} >&2
    found=1
    break
  fi
done

if test x$found = x; then
  echo UNIT_OBJS+=-ltrt${suffix} >&3
fi
