#! /bin/sh
#
# prcgen-sh :  rpcgen workaround
#           
# This file is a part of GNU SQL Server
#
# Contacts: gss@ispras.ru
#

rpcgen=$1
option=$2
incdir=$3
proto=$4
# =======================================
external_srcdir=no
include_h_brakets=no
# parse option
for opt in $option ; do
  case $opt in
  Ihdr) # include additional comments
    include_h_brakets=yes
     ;;
  *) ;;
  esac
done
# ------------
libdir=`echo $0 | tr '/' '|' | sed "s/|rpcgen-sh//g" | tr '|' '/' `
fname=`echo $proto | tr '/' '|' | sed "s/\.x//g;s/.*|//g" | tr '|' '/' `
macro_fname=`echo $fname | tr '[a-z]' '[A-Z]' | tr '.' '_' | tr '-' '_' `

if [ "x$incdir" = "x" ];  then
  echo target directory name is empty
  exit 1
fi
if [ "x$fname"  = "x" ]; then
  echo empty protocol file name 
  exit 1
fi
if [ ! -f $fname.x ]; then
  cp $proto $fname.x
  external_srcdir=yes
fi
echo "  rpcgen $fname.x --> $incdir/$fname.h"
$1 $fname.x
if [ "$external_srcdir" = "yes" ]; then
  rm -f $fname.x
fi
tmpfile=__tmp__
proto_h=$incdir/$fname.h
[ -f $tmpfile ] || rm -f $tmpfile
if [ "$include_h_brakets" = "yes" ]; then
  echo "#ifndef _${macro_fname}_RPCGEN " >  $tmpfile
  echo "#define _${macro_fname}_RPCGEN " >> $tmpfile
  echo "                               " >> $tmpfile
  echo "#ifndef  RPC_H_RPCGEN          " >> $tmpfile
  echo "# define  RPC_H_RPCGEN         " >> $tmpfile
  echo "                               " >> $tmpfile
  echo '# include <rpc/rpc.h>          ' >> $tmpfile
  echo "                               " >> $tmpfile
  echo '# include "setup_os.h"         ' >> $tmpfile
  echo '# if TIME_WITH_SYS_TIME        ' >> $tmpfile
  echo '#  include <sys/time.h>        ' >> $tmpfile
  echo '#  include <time.h>            ' >> $tmpfile
  echo '# else                         ' >> $tmpfile
  echo '#  if HAVE_SYS_TIME_H          ' >> $tmpfile
  echo '#   include <sys/time.h>       ' >> $tmpfile
  echo '#  else                        ' >> $tmpfile
  echo '#   include <time.h>           ' >> $tmpfile
  echo '#  endif                       ' >> $tmpfile
  echo "# endif                        " >> $tmpfile
  echo '#endif                         ' >> $tmpfile
  echo "                               " >> $tmpfile
fi
cat $fname.h >>$tmpfile
rm  $fname.h
if [ "$include_h_brakets" = "yes" ]; then
  echo "#endif /*_${macro_fname}_RPCGEN*/" >>$tmpfile
fi
if [ -f $proto_h ]; then
   rm -f $proto_h
fi
$libdir/move-if-change mv $tmpfile $proto_h
if [ "$include_h_brakets" = "yes" ]; then
 # we have already added '#include <rpc/rpc.h>' and '...time.h'
 # now we need to eliminate such includes from generated stubs
 for stub in ${fname}_svc.c ${fname}_clnt.c ${fname}_xdr.c ; do
   sed "s/^#include.*rpc[.]h>//g;s/^#include.*time[.]h>//g" ${stub} >$tmpfile
   $libdir/move-if-change mv $tmpfile ${stub}
 done
fi
