/**
 * File: subprocess.c
 * ------------------
 * Implements the subprocess routine, which is similar to popen and allows
 * the parent process to spawn a child process, print to its standard output,
 * and then suspend until the child process has finished.
 */

#include <fcntl.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>
#include "stsh-parser/stsh-parse.h"
#include "fork-utils.h" // this needs to be the last #include in the list


// A struct that stores a PID and FD we can write to
typedef struct subprocess_t {
    pid_t pid;
    int supplyfd;
} subprocess_t;

/* subprocess runs the given shell command in the background
 * in a child process and returns the PID of that child process
 * as well as a file descriptor we can write to to write to that
 * child's STDIN.
 */
subprocess_t subprocess(const char *command) {
    // TODO

    /*
    // This is the code from our first shell example
    const command& command = p.commands[0];

    pid_t pidOrZero = fork();
    if (pidOrZero == 0) {
      // If we are the child, execute the command
      execvp(command.argv[0], command.argv);
      // If the child gets here, there was an error
    }

    // If we are the parent, wait for the child
    waitpid(pidOrZero, NULL, 0);
    */
}

int main(int argc, char *argv[]) {
    // Spawn a child that is running the grep command
    //subprocess_t sp = subprocess("/usr/bin/grep -E Sunny|Cloudy");
    subprocess_t sp = subprocess("/usr/bin/grep Sunny");

    // We want to feed these lines as input to grep to print only sunny days
    const char * recent_weather[] = { "Sunny 72", "Rainy 55", "Cloudy 62",
        "Sunny 80", "Sunny 75", "Cloudy 61", "Sunny 68", "Rainy 60", "Sunny 85"
    }; 
    size_t nelems = sizeof(recent_weather) / sizeof(recent_weather[0]);

    // write each entry on its own line to the STDIN of the child process
    for (size_t i = 0; i < nelems; i++) {
        dprintf(sp.supplyfd, "%s\n", recent_weather[i]);
    }

    // Close the write FD to indicate the input is closed
    close(sp.supplyfd);

    // Wait for the child to finish before exiting
    waitpid(sp.pid, NULL, 0);
    return 0;
}
