/* =============================================================================
 * 04_redirect.c -- dup2: how the shell implements "command > file"
 * =============================================================================
 *
 * [Idea]
 *   printf writes to descriptor 1. It has no idea whether descriptor 1 is your
 *   terminal, a file or a pipe -- and that is the whole trick behind redirection.
 *   To implement `ls > out.txt`, the shell does NOT change ls. It forks, and in
 *   the child, BEFORE exec'ing ls, it makes descriptor 1 point at the file:
 *
 *       int fd = open("out.txt", O_WRONLY|O_CREAT|O_TRUNC, 0644);
 *       dup2(fd, STDOUT_FILENO);     /@ fd 1 now refers to out.txt @/
 *       execve("/bin/ls", ...);      /@ ls prints to fd 1 == the file @/
 *
 *   dup2(old, new) makes `new` a copy of `old`, closing whatever `new` referred
 *   to first. The program being redirected needs no cooperation at all.
 *
 *   This demo redirects its OWN stdout to a file, prints, then puts stdout back
 *   and reads the file to prove where the text went.
 *
 * [What it answers]
 *   - What does dup2 do, exactly, and why does it close the target first?
 *   - How is redirection implemented without the program's knowledge?
 *   - How do you restore stdout afterwards? (save a copy with dup first)
 *
 * Build & run:    make run
 * -----------------------------------------------------------------------------
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include "rio.h"

#define PATH "build/04_redirected.txt"

int main(void)
{
    printf("[1] this line goes to the terminal (fd 1 = your screen)\n");
    fflush(stdout);     /* [C tip] flush BEFORE moving fd 1, or buffered text
                           would be written to the NEW destination later. */

    /* ---- save the current stdout so we can come back --------------------- */
    /* dup() returns a new descriptor for the same open-file entry (Lecture 18
       demo 03): saved_stdout is now a second handle on the terminal. */
    int saved_stdout = dup(STDOUT_FILENO);
    if (saved_stdout < 0) { perror("dup"); return 1; }

    /* ---- redirect: make fd 1 refer to the file --------------------------- */
    int fd = open(PATH, O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (fd < 0) { perror("open"); return 1; }

    if (dup2(fd, STDOUT_FILENO) < 0) { perror("dup2"); return 1; }
    close(fd);          /* fd 1 holds the reference now; this copy is redundant */

    /* Everything printed from here lands in the FILE, not the terminal. */
    printf("[2] this line goes into the file\n");
    printf("[3] ...and so does this one\n");
    fflush(stdout);     /* push it out while fd 1 still points at the file */

    /* ---- restore stdout -------------------------------------------------- */
    dup2(saved_stdout, STDOUT_FILENO);
    close(saved_stdout);

    printf("[4] stdout restored: this line is on the terminal again\n");

    /* ---- prove it by reading the file back ------------------------------- */
    int in = open(PATH, O_RDONLY);
    if (in < 0) { perror("open for read"); return 1; }
    char buf[256];
    ssize_t n = rio_readn(in, buf, sizeof(buf) - 1);
    buf[n > 0 ? n : 0] = '\0';
    close(in);

    printf("\n[file] '%s' now contains %zd bytes:\n", PATH, n);
    /* indent each line of the captured text so it is easy to see */
    for (char *line = strtok(buf, "\n"); line; line = strtok(NULL, "\n"))
        printf("       | %s\n", line);

    printf("\nObservations\n------------\n");
    printf("- Lines [2] and [3] never reached the terminal; they are in the\n");
    printf("  file. printf did not change -- descriptor 1 did.\n");
    printf("- dup2(fd, 1) silently CLOSED the old fd 1 first, which is why the\n");
    printf("  terminal had to be saved with dup() beforehand to get it back.\n");
    printf("- This is exactly the shell's '>' : fork, dup2 in the child, exec.\n");
    printf("  The redirected program needs no cooperation and cannot tell.\n");
    return 0;
}

/*
 * Observations (author's machine, Apple M4 Pro, macOS):
 *   [1] this line goes to the terminal (fd 1 = your screen)
 *   [4] stdout restored: this line is on the terminal again
 *
 *   [file] 'build/04_redirected.txt' now contains 61 bytes:
 *          | [2] this line goes into the file
 *          | [3] ...and so does this one
 *
 *   - Lines [2]/[3] are absent from the terminal output and present in the
 *     file: redirection happened entirely in the descriptor table.
 *   - The byte count is whatever the two lines total; it is read back from the
 *     real file rather than assumed.
 */
