#!/bin/sh
# --------------------------------------------------------------------------
# Copyright 1992 by Forschungszentrum Informatik (FZI)
#
# You can use and distribute this software under the terms of the license
# version 1 you should have received along with this software.
# If not or if you want additional information, write to
# Forschungszentrum Informatik, "STONE", Haid-und-Neu-Strasse 10-14,
# D-76131 Karlsruhe, Germany.
# --------------------------------------------------------------------------
# 'obst-scp - 06:06:91 - Dietmar Theobald'
#
# obst-scp [<schema>] [-o <outfile>] <infile>
#
# 'obst-scp' calls the OBST C++ preprocessor 'scp' on <infile>.
# <infile> contains method implemetations for <schema>, output is written to
# <outfile>.
#
# <schema> may be omitted if the directory containing <infile> contains a single
# schema file '*.obst'. In this case <schema> will be set to '*'.
#
# <outfile> may be omitted if <infile> is matched by '*.c', '*.cc', or '*.C'.
# In this case output will be written to '*_scp.<ext>' in the same directory as
# <infile>, where <ext> will be the same as the ending of <infile>.
#
[ -n "$OBSTdir" ] || { OBSTdir="`cd \`dirname $0\`;pwd`/"; export OBSTdir; }

 self='obst-scp'
usage='[<schema>] <infile> [-o <outfile>]'

if [ -z "$OBSTCONTAINER" -a -z "$SOSCONTAINER" ] ; then
  echo >&2 "*** $self: environment variable OBSTCONTAINER not defined"
  exit 1
fi

tmpfile=/tmp/$self$$

while [ $# -gt 0 ] ; do
   case "$1" in
	       -o) shift
		   [ "$outfile" ] && { err='+'; break ;} ; outfile="$1" ;;
      *.[Cc]|*.cc) [ "$infile"  ] && { err='+'; break ;} ;  infile="$1" ;;
		*) [ "$schema"  ] && { err='+'; break ;} ;  schema="$1" ;;
   esac
   shift
done
if [ -z "$infile"  -o  $# -gt 0  -o -n "$err" ] ; then
   err='+'
else
   indir="`dirname $infile`"
   [ "$schema" ] || {
      for f in $indir/*.obst $indir/*.sos
      do
	 [ -f "$f" ] 2>/dev/null && {
	    [ "$schema" ] && {
	       echo >&2 "*** $self: several OBST schema files in $indir"
	       exit 1; }
	    schema=`echo "/$f" | sed 's|.*/\(.*\)\..*|\1|'`; }
      done
      [ "$schema" ] || {
	 echo >&2 "*** $self: no OBST schema file in $indir"; exit 1; }
      }
   [ "$outfile" ] || {
      outfile=`echo "$infile" | sed -n -e 's|\(.*\)\(\.[^.]*\)|\1_scp\2|p'`
      [ "$outfile" ] || err='+'
      }
fi
[ "$err" ] && { echo >&2 "*** usage: $self $usage"; exit 1; }

[ -f "$infile" ] || { echo >&2 "*** $self: no file $infile"; exit 1; }

[ -d `dirname $outfile` ] || {
   echo >&2 "*** $self: no directory `dirname $outfile`"; exit 1; }

trap "rm -f $tmpfile; exit 1" 1 2 3 6 10 15

#echo "[$self: ${OBSTdir}scp $infile --> $outfile]"

${OBSTdir}scp $schema $infile > $tmpfile || { rm -f $tmpfile ; exit 1 ;}

rm -f $outfile
cat $tmpfile > $outfile
rm -f $tmpfile
