/* $Id: ps_init.c,v 1.2 90/11/29 18:33:03 altenhof Exp $ */

/*
 * Copyright (C) 1990 by Digital Equipment Corporation.
 * 
 * Author: Michael P. Altenhofen, CEC Karlsruhe e-mail:
 * Altenhofen@kampus.enet.dec.com
 * 
 * This file ist part of Shared X
 * 
 * Permission to use, copy, modify, and distribute this software and its
 * documentation without fee is hereby granted, but only for non-profit  use
 * and distribution,  and provided  that the copyright notice and this notice
 * is preserved on all copies.
 * 
 * DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
 * ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
 * DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
 * ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
 * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
 * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
 * SOFTWARE.
 */

#define PUBLIC extern

#define _USE_STRUCTS_
#define _XEVENTS_

#include "glob.h"

#include "connection.h"
#include "utils.h"
#include "dispatch.h"
#include "resources.h"
#include "map.h"

#undef PUBLIC

#include <stdio.h>

static char* version = VERSION;

void
CreateClient ()
{
  register int muxServer_fd;

  if ((muxClient = NextAvailableClient ()) == NullClient)
    FatalError ("CreatemuxClient: allocation failure!\n ");

  muxClient->xdpy = OpenServerConnection (defaultClientID, defaultServer);
  if (!muxClient->xdpy)
    FatalError ("CreateClient: Can't create connection!\n");
}

void
usage (prog_name)
  char *prog_name;
{
  fprintf (stderr, "usage: %s [-options ...]\n\n", prog_name);
  fprintf (stderr, "options:\n");

 /*****************************************************************
  fprintf (stderr , 
	   "-requests    print requests sent by application\n");
  fprintf (stderr ,
	   "-events      print events received by application\n");
  fprintf (stderr ,
	   "-resources   print information about application resources \n");
  fprintf (stderr , 
	   "-io          print io information\n");
  *****************************************************************/

  fprintf (stderr,
	   "-d <server>  \"real\" server you want to contact\n");
  fprintf (stderr,
	   "-n number shXbridge's connection number (default = 2)\n");

 /*****************************************************************
  fprintf (stderr , "-f <filename>   log file ( default is stderr )\n" ) ;
  *****************************************************************/
  exit (1);
}

void
ParseCommandLine (argv, argc)
  char *argv[];
  int argc;
{
  register int i;

  _debug_requests =
    _debug_events =
    _debug_resources =
    _debug_io =
    _debug_alloc = FALSE;
  display_name = "2";

  for (i = 1; i < argc; i++) {
    if (!strcmp (argv[i], "-requests")) {
      _debug_requests = TRUE;
      continue;
    }
    if (!strcmp (argv[i], "-events")) {
      _debug_events = TRUE;
      continue;
    }
    if (!strcmp (argv[i], "-resources")) {
      _debug_resources = TRUE;
      continue;
    }
    if (!strcmp (argv[i], "-io")) {
      _debug_io = TRUE;
      continue;
    }
    if (!strcmp (argv[i], "-display")) {
      defaultServer = argv[++i];
      continue;
    }
    if (!strcmp (argv[i], "-n")) {
      display_name = argv[++i];
      continue;
    }
    if (!strcmp (argv[i], "-f")) {
      if ((logfile = fopen (argv[i + 1], "w")) == (FILE *) 0) {
	logfile = (FILE *) 0;
	ErrorF ("Can,t open file %s ( use stderr )\n", argv[i + 1]);
      }
      else
	i++;
      continue;
    }
    usage (argv[0]);
  }
}

int
PSErrorHandler (dpy, error)
  Display *dpy;
  XErrorEvent *error;
{
  error->serial = LastKnownRequestProcessed (dpy) -
    ServerAhead[ConnectionNumber (dpy)];
  ErrorF ("Error on connection number %d!\n",
	  ConnectionNumber (dpy));
  /* print parts of standard error text */
  PrintError (dpy, error);

  /*
   * Use global clientErrorValue and clientErrorRequest to report the
   * error back
   */
  clientErrorValue = error->error_code;
  clientErrorRequest = error->request_code;
  return (0);
}

int
PSIOErrorHandler (dpy)
  Display *dpy;
{
  register int i;
  ClientPtr client;

  ErrorF ("X I/O error-->closing connection %d\n",
	  ConnectionNumber (dpy));

  client = ClientFromDisplay (dpy);
  if (client) {
    if (CloseDownClient (client, TRUE))
      longjmp (jmpenv, 1);
  }
  else if (CloseDownServer (dpy, TRUE))
    longjmp (jmpenv, 1);
}

void
Initialize (looping, argv, argc)
  int looping;
  char *argv[];
  int argc;
{
  register int i;
  char *progname;
  char hostname[32];

  progname = argv[0];

  currentMaxClients = 10;
  clients = (ClientPtr *)
    Xmalloc (currentMaxClients * sizeof (ClientPtr));
  for (i = 0; i < currentMaxClients; i++)
    clients[i] = NullClient;

  if (!looping) {
    MaxClients = MAXSOCKS;

    ParseCommandLine (argv, argc);
    CreateWellKnownSockets ();
    CreateClient ();
    XSetErrorHandler (PSErrorHandler);
    XSetIOErrorHandler (PSIOErrorHandler);
  }
  for (i = 0; i < MAXSOCKS; i++)
    ServerAhead[i] = 0;
  _InitIDMaps ();

  gethostname (hostname, 32);
  debug (TRUE, "\nReady! (connected to %s)\n", defaultServer);
  debug (TRUE,
	 "(%s v%s is listening for clients on connection %s:[:]%s)\n",
	 progname, version, hostname, display_name);
}
