/*
 * PJ Waskiewicz
 * 2/08/2000
 * redirect.c
 * Function to perform I/O redirection in pnsh
 *
 */

#include "pnsh.h"

void redirect(char **args, int i) {
  int fd;
  /* Now get ready for redirecting I/O */
  if(strcmp(args[i], "<") == 0) {
    if(args[i + 1] == NULL)
      fprintf(stderr, "%s: Bad form\n", args[0]);
    else {
      /* Now get ready to fork and exec */
      args[i] = NULL;
      if(fork() == 0) {
        /* Open the file */
        if((fd = open(args[i + 1], O_RDONLY)) < 0)
          fprintf(stderr, "%s: open() in child\n", strerror(errno));
        if((fd = dup2(fd, 0)) < 0)
          fprintf(stderr, "%s: dup2() in child\n", strerror(errno));
        /* I'm the child.  I'll exec... */
        if(execvp(args[0], args) < 0)
          /* Something bad happened */
          fprintf(stderr, "%s: %s\n", args[0], strerror(errno));
      }
      else {
        /* I'm the parent.  I'm going to wait for the child to go away */
        if(wait(NULL) < 0)
            fprintf(stderr, "%s: wait() in parent\n", strerror(errno));
      }
    }
  }
  else if(strcmp(args[i], ">") == 0) {
    /* Now get ready to fork and exec */
    if(args[i + 1] == NULL)
      fprintf(stderr, "%s: Bad form\n", args[0]);
    else {
      args[i] = NULL;
      if(fork() == 0) {
        /* First open the file */
        if((fd = open(args[i + 1], O_RDWR | O_CREAT | O_TRUNC, 0666)) < 0)
          fprintf(stderr, "%s: open() in child\n", strerror(errno));
        /* Purge the file */
        if((fd = dup2(fd, 1)) < 0)
          fprintf(stderr, "%s: dup2() in child\n", strerror(errno));
        /* I'm the child.  I'll exec... */
        if(execvp(args[0], args) < 0)
          /* Something bad happened */
          fprintf(stderr, "%s: %s\n", args[0], strerror(errno));
      }
      else {
        /* I'm the parent.  I'm going to wait for the child to go away */
        if(wait(NULL) < 0)
          fprintf(stderr, "%s: wait() in parent\n", strerror(errno));
      }
    }
  }
}