/**
 * File: first-shell.c
 * ----------------
 * A program containing an implementation of a working shell that can
 * execute entered text commands.  It relies on our own custom implementation
 * of system(), called executeCommand(), that creates a process to execute 
 * a given shell command.
 */

#include <stdio.h>
#include <unistd.h>
#include <stdbool.h>
#include <sys/wait.h>
#include "string.h"
#include "exit-utils.h"
#include "sleep-utils.h"

// The max-length shell command the user can enter
static const size_t kMaxLineLength = 2048;

// The exit status for the child if the exec fails
static const int kExecFailed = 1;

// The currently-running foreground command PID
static pid_t foregroundPID = 0;


/* Function: updateSIGCHLDBlock
 * ---------------------------
 * Parameters:
 *    block - true if we should block SIGCHLD, false if we should unblock SIGCHLD
 *
 * Returns: N/A
 *
 * Adds or removes a block on SIGCHLD depending on the value of `block`.  The rest
 * of the blocked signal set stays the same.
 */
void updateSIGCHLDBlock(bool block) {
    sigset_t sigchldMask;
    sigemptyset(&sigchldMask);
    sigaddset(&sigchldMask, SIGCHLD);
    sigprocmask(block ? SIG_BLOCK : SIG_UNBLOCK, &sigchldMask, NULL);
}


/* Function: waitForForegroundCommand
 * ----------------------------
 * Parameters:
 *     pid - the pid of the foreground process to wait for
 *
 * Returns: N/A
 * Blocks to wait for the foreground process to finish.  This function sets
 * the global foregroundPID variable equal to this pid, and then waits for the
 * child handler to change it to 0, indicating that the process has finished.
 */
static void waitForForegroundCommand(pid_t pid) {
    foregroundPID = pid;
    sigset_t emptySet;
    sigemptyset(&emptySet);
    while (foregroundPID == pid) {
        sigsuspend(&emptySet);
    }
    updateSIGCHLDBlock(false);
}


/* Function: executeCommand
 * ------------------
 * Parameters:
 *     command - the shell command to execute in another process
 *     inBackground - whether to run the command in the background or block until finished
 *
 * This function executes the given shell command using /bin/sh.
 * It executes it in another process, and waits for that process to complete
 * if run in the foreground, or immediately returns if run in the background.
 */
static void executeCommand(char *command, bool inBackground) {
    updateSIGCHLDBlock(true);
    pid_t pidOrZero = fork();
    if (pidOrZero == 0) {
        updateSIGCHLDBlock(false);
        // If we are the child, execute the shell command
        char *arguments[] = {"/bin/sh", "-c", command, NULL};
        execvp(arguments[0], arguments);
        // If the child gets here, there was an error
        exitIf(true, kExecFailed, stderr, "execvp failed to invoke this: %s.\n", command);
    }

    // If we are the parent, either wait or return immediately
    if (inBackground) {
        printf("%d %s\n", pidOrZero, command);
        updateSIGCHLDBlock(false);
    } else {
        waitForForegroundCommand(pidOrZero);
    }
}


/* Function: reapProcesses
 * -----------------------
 * Parameters: 
 *    signum - the signal that caused this handler to be called
 * 
 * Returns: N/A
 * 
 * A signal handler function for SIGCHLD that cleans up all terminated
 * children that resulted in the signal being sent.  It also updates the
 * foregroundPID global variable to store the PID of the most recent
 * child that terminated.
 */
static void reapProcesses(int signum) {
    printf("Reaping 1+ children...\n");
    while (true) {
        pid_t result = waitpid(-1, NULL, WNOHANG);
        if (result <= 0) break;
        if (result == foregroundPID) foregroundPID = 0;
    }
}


/* Function: main
 * --------------
 * This main function contains the main read-evaluate loop
 * for the shell that continues to prompt the user for a command
 * and executes the command in a created child process.  If the
 * user ends the command with '&', the command is executed
 * without waiting for the command to terminate.  The "quit"
 * command terminates the shell loop and ends the program.
 */
int main(int argc, char *argv[]) {
    char command[kMaxLineLength];
    signal(SIGCHLD, reapProcesses);
    while (true) {
        printf("> ");
        fgets(command, sizeof(command), stdin);
    
        // If the user entered Ctl-d, stop
        if (feof(stdin)) {
            break;
        }
    
        // Remove the \n that fgets puts at the end
        command[strlen(command) - 1] = '\0';

        if (strcmp(command, "quit") == 0) {
            break;
        }

        bool isbg = command[strlen(command) - 1] == '&';
        if (isbg) {
            command[strlen(command) - 1] = '\0';
        }

        executeCommand(command, isbg);
    }
  
    printf("\n");
    return 0;
}
