/* tcld.c -- Remote Debugger interface.
 * tromey Fri Jul 15 1994
 */

/* TODO:
 * Needs way to list all possible debugees.
 * Needs way to clean debugger directory.
 * Should use select loop for more flexibility.
 */

#include <assert.h>
#include <stdio.h>
#include <malloc.h>

#include "tcl.h"

#include "Dbgtkint.h"



/*
 * This is here so we don't have to link with Tk.
 */
void Tk_CreateFileHandler ()
{
  assert (0);
}



int main (argc, argv)
int argc;
char *argv[];
{
  char buffer[1000];
  char *str, *cmd;
  Tcl_Interp *interp;
  Tcl_DString command;
  int pid;
  int fd;

  if (argc != 2)
    {
      fprintf (stderr, "usage: tcld pid\n");
      exit (1);
    }

  interp = Tcl_CreateInterp ();

  if (Tcl_GetInt (interp, argv[1], &pid) != TCL_OK)
    {
      /* FIXME use Tcl error message. */
      fprintf (stderr, "tcld: pid %s not a number\n", argv[1]);
      exit (1);
    }

  fd = Dbg_connect_to_server (interp, pid);
  if (fd == -1)
    {
      fprintf (stderr, "tcld: %s\n", interp->result);
      exit (1);
    }

  Tcl_DStringInit (&command);
  while (1)
    {
      int first;

      /* Read from client first, because debugger prints stuff on */
      /* startup. */
      while (1)
	{
	  str = Dbg_read (fd);
	  if (str == NULL)
	    {
	      fprintf (stderr, "tcld: error while reading from pipe\n");
	      exit (1);
	    }
	  if (*str == '\0')
	    break;
	  fprintf (stderr, "%s", str);
	  free (str);
	}
      fprintf (stderr, "\n", str);

      clearerr (stdin);
      first = 1;
      while (1)
	{
	  fputs (first ? "tcld> " : "tcld+ ", stdout);
	  fflush (stdout);
	  first = 0;

	  if (fgets (buffer, 1000, stdin) == NULL)
	    exit (0);

	  cmd = Tcl_DStringAppend (&command, buffer, -1);
	  if (Tcl_CommandComplete (cmd))
	    break;
	}

      if (!Dbg_write (fd, cmd) || !Dbg_mark (fd))
	{
	  /* Error. */
	  perror ("tcld: error writing to pipe");
	  exit (1);
	}

      Tcl_DStringFree (&command);
    }

  exit (0);
}
