# include <ohana.h>

int ForkToServer (int argc, char **argv, char *database, char *server) {

  int i, fd, N, pid, status;
  char **arglist, *p;
  char hostname[1025];
  struct timeval now, then;  
  double dtime;

  /* get local hostname */
  if (gethostname (hostname, 1024)) {
    fprintf (stderr, "ERROR: can't get hostname\n");
    exit (1);
  }

  /* lock database file */
  fd = setlockfile (database, 60.0, TRUE);
  if (fd == -1) {
    fprintf (stderr, "ERROR: can't set lock on %s\n", database);
    exit (1);
  }

  if ((p = strchr (server, '.')) != (char *) NULL) *p = 0;
  if ((p = strchr (hostname, '.')) != (char *) NULL) *p = 0;

  if (!strcasecmp (hostname, server)) return (fd);

  if (!strlen (server)) {
    fprintf (stderr, "ERROR: no Database Server defined\n");
    clearlockfile (database, fd, TRUE);
    exit (1);
  }

  /* get start of fork time */
  gettimeofday (&then, (void *) NULL);
  pid = fork ();
  if (!pid) { 
    /* must be child process, fork to remote machine */

    /* create argument list */
    N = argc + 4;
    ALLOCATE (arglist, char *, N);

    arglist[0] = strcreate ("rsh");
    arglist[1] = strcreate (server);
    arglist[2] = strcreate (argv[0]);
    arglist[3] = strcreate ("-remote");
    for (i = 4; i < N; i++) {
      arglist[i] = strcreate (argv[i-3]);
    }
    fprintf (stderr, "starting remote process on %s\n", server);
    status = execvp ("rsh", arglist);
    fprintf (stderr, "ERROR: can't start remote shell process\n");
    exit (1);
  }
  /* it would be good to put rsh in the config file */

  /* block until child exits */
  wait (0);
  
  /*****  
       inetd has a maximum connection rate of 40 / 60 seconds it will
       block for 10 min if this rate is exceeded.  this is here because
       we have to hold the lock long enough that the connection rate does
       not get exceeded.  We actually use 3.0 seconds to avoid stealing
       too many rsh slots. 
  *****/
  
  gettimeofday (&now, (void *) NULL);
  dtime = 1e6*(3.0 - DTIME(now,then));
  if (dtime > 0) usleep (dtime);
  
  clearlockfile (database, fd, TRUE);
  exit (0);
  
}
