#! /bin/sh
#
# Helper script to create RPC source files
#
# Usage: mkrpc srcdir destdir
srcdir=$1
dstdir=$2
RPCGEN="rpcgen -C"
XDR_FILE=$srcdir/rpc/db_server.x
$RPCGEN -h $XDR_FILE > $dstdir/db_server.h 2> /dev/null
[ $? -ne 0 ] && {
  RPCGEN=rpcgen
  $RPCGEN -h $XDR_FILE > $dstdir/db_server.h 2> /dev/null
  [ $? -eq 0 ] || {
    echo "RPCGEN failed!"
    exit 1
  }
}

# Some rpcgen programs generate a set of client stubs called something
# like __db_env_create_4003 and functions on the server to handle the
# request called something like __db_env_create_4003_svc.  Others
# expect client and server stubs to both be called __db_env_create_4003.
#
# We have to generate code in whichever format rpcgen expects, and the
# only reliable way to do that is to check what is in the db_server.h
# file we just created.
if grep "env_create_[[0-9]]*_svc" $dstdir/db_server.h >/dev/null 2>&1 ; then
  sed 's/__SVCSUFFIX__/_svc/' \
    < $srcdir/rpc/gen_db_server.c > $dstdir/gen_db_server.c
else
  sed 's/__SVCSUFFIX__//' \
    < $srcdir/rpc/gen_db_server.c > $dstdir/gen_db_server.c
fi

$RPCGEN -l $XDR_FILE |
  sed -e 's/^#include.*db_server.h.*/#include "db_server.h"/' \
      -e '1,/^#include/s/^#include/#include "db_config.h"\
&/' > $dstdir/db_server_clnt.c

$RPCGEN -s tcp $XDR_FILE |
  sed -e 's/^#include.*db_server.h.*/#include "db_server.h"/' \
      -e 's/^main *()/__dbsrv_main()/' \
      -e 's/^main *(.*argc.*argv.*)/__dbsrv_main(int argc, char *argv[])/' \
      -e '/^db_rpc_serverprog/,/^}/{' \
      -e 's/return;//' \
      -e 's/^}/__dbsrv_timeout(0);}/' \
      -e '}' \
      -e '1,/^#include/s/^#include/#include "db_config.h"\
&/' > $dstdir/db_server_svc.c

$RPCGEN -c $XDR_FILE |
  sed -e 's/^#include.*db_server.h.*/#include "db_server.h"/' \
      -e '1,/^#include/s/^#include/#include "db_config.h"\
&/' > $dstdir/db_server_xdr.c

exit 0
