 /****************************************************************************\
| callcld.c -- execute a program and redirect its output to a given tty        |
| usage: callcld -c "exec progname [arg0 arg1...]"                             |
| (c) 1994 by HighTec EDV-Systeme GmbH, 05/13/94 (ms)                          |
 \****************************************************************************/

#include <stdio.h>
#include <string.h>
#include <sys/fcntl.h>
#include <sys/signal.h>

#define MAX_ARGS 1000
#define TEST 0

extern char *getenv();
char *ptty, *xargv[MAX_ARGS];
int xargc;

void build_args(int argc, char *argv[])
{
  register int  len;
  register char *cp, *cp2, *arg;


  if ((argc != 3) || strcmp(argv[1], "-c") || strncmp(argv[2], "exec ", 5))
  { fprintf(stderr, "%s: called with more than 2 or illegal args.\n", argv[0]);
    exit(1);
  }
  xargc = -1;
  for (cp = &argv[2][5]; *cp != '\0'; ++cp)
  { if ((*cp == ' ') || (*cp == '\t'))
      continue;
    if (*cp == '"')
    { ++cp;
      for (cp2 = cp; *cp2 != '\0'; ++cp2)
      { if ((*cp2 == '\\') && (*(cp2+1) == '"'))
	  cp2 += 2;
	else if (*cp2 == '"')
	  break;
      }
      if (*cp2 == '"')
        *cp2 = ' ';
    }
    else
    { for (cp2 = cp+1; ; ++cp2)
        if ((*cp2 == ' ') || (*cp2 == '\t') || (*cp2 == '\0'))
	  break;
    }
    len = (int)(cp2-cp)+1;
    if ((arg = (char *)malloc(len)) == NULL)
    { fprintf(stderr, "%s: can't malloc().\n", argv[0]);
      exit(1);
    }
    strncpy(arg, cp, len); arg[len-1] = '\0';
    if (++xargc == MAX_ARGS)
    { fprintf(stderr, "%s: more than %d arguments.\n", argv[0], MAX_ARGS);
      exit(1);
    }
    xargv[xargc] = arg;

    if (*(cp = cp2) == '\0')
      break;
  }
  xargv[++xargc] = NULL;

# if TEST
  { int i;

    printf("ptty = <%s>\n", ptty);
    for (i = 0; i <= xargc; ++i)
      printf("xarg(%d) = <%s>\n", i, xargv[i]);
    exit(0);
  }
# endif
}
/******************************************************************************/
void main(int argc, char *argv[], char *envp[])
{
  int  desc0, desc1, desc2;


# if TEST
  { int i;
    char buffer[1000];

    for (i = 0; i < argc; ++i)
    { sprintf(buffer, "arg(%d) = <%s>\n", i, argv[i]);
      write(1, buffer, strlen(buffer));
    }
  }
# endif
  build_args(argc, argv);
  ptty = getenv("TGDB_TTYDEV");
  if (ptty == NULL)
  { fprintf(stderr, "%s: no tty specified.\n", argv[0]);
    exit(1);
  }
  desc0 = open(ptty, O_RDONLY);
  desc1 = open(ptty, O_WRONLY);
  desc2 = open(ptty, O_WRONLY);
  if ((desc0 < 0) || (desc1 < 0) || (desc2 < 0))
  { fprintf(stderr, "%s: can't open %s\n", argv[0], ptty);
    exit(1);
  }
  close(0); close(1); close(2);
  dup(desc0); dup(desc1); dup(desc2);
  close(desc0); close(desc1); close(desc2);
  execvp(xargv[0], xargv);
  fprintf(stderr, "%s: can't exec()\n", argv[0]);
  exit(1);
}
