/*==========================================================================*\
 |  This file is part of setiherder (http://www.sackheads.org/setiherder/)  |
 |  which was written by Brian L. Naylor <brian+seti@sackheads.org> and is  |
 |  under the GNU General Public License.  You should have recieved a copy  |
 |  of the GPL with this source code.  If not, we'd like to know about it.  |
\*--------------------------------------------------------------------------*/

/*
 * Originally 'pty.c' from Andy Sloane's 'setiview' program
 */

#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include "setiview-pty.h"

static int find_tty(sh_client_t *child)
{
#ifdef BSD
  int *i, *j;
#else
  int i, j;
#endif
  int fd, fd2;
  char devname[128];

  strcpy(devname, "/dev/ptyXX");

#ifdef BSD
  for(j="pqrsPQRS"; *j; j++) {
    devname[8] = *j;
    for(i="0123456789abcdefghijklmnopqrstuv"; *i; i++) {
      devname[9] = *i;
#else
  for(j='p'; j<='s'; j++) {
    devname[8] = j;
    for(i='0'; i<='9'; i++) {
      devname[9] = i;
#endif   
      fd = open(devname, O_RDONLY);
      /* can we access pty device? */
      if(fd != -1) {
        /* can we access tty device? */
        devname[5] = 't';
        fd2 = open(devname, O_WRONLY);
        if(fd2 != -1) {
          child->ptyfp = fdopen(fd, "r");
          child->ttyfp = fdopen(fd2, "w");
          return 1;
        }
        /* no, try more ptys */
        devname[5] = 'p';
        close(fd);
      }
    }
  }
  return 0;
}

FILE *pty_alloc(sh_client_t *child)
{
  if(!find_tty(child)) {
    printf("pty_alloc() Can't allocate pseudotty!\n");
    return NULL;
  }

  setlinebuf(child->ptyfp);
  return child->ptyfp;
}

void pty_fork(char **argv, int *pid)
{
#if 0   /* I don't need this */
  FILE *fp;
  if(!(*pid = fork())) {
    dup2(fileno(ttyfp), fileno(stdout));
    execvp(argv[0], argv);
    exit(-1);
  }
#endif
}

void pty_close(sh_client_t *child)
{
  fclose(child->ptyfp);
  fclose(child->ttyfp);
}

