/* =============================================================================
 * 01_unix_io.c -- the four calls everything else is built on
 * =============================================================================
 *
 * [Idea]
 *   Every file, pipe, socket, terminal and device in Unix is read and written
 *   through the SAME four system calls: open, read, write, close (plus lseek to
 *   move around). That uniformity is the "everything is a file" design: once you
 *   have a descriptor you do not care what is behind it. printf, fopen, sockets
 *   and the shell are all layered on top of these.
 *
 *   This demo walks the whole life cycle of a file: create it, write to it, ask
 *   the kernel about it (stat), read it back, seek inside it, and copy it --
 *   using the RIO wrappers so short counts cannot lose data.
 *
 * [What it answers]
 *   - What is a file descriptor, and which three are always open?
 *   - What does open()'s flags/mode mean, and what does lseek() actually move?
 *   - What metadata does the kernel keep per file (stat), and how do you read it?
 *
 * Build & run:    make run        (writes its scratch files under build/)
 * -----------------------------------------------------------------------------
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>          /* open, O_* flags */
#include <sys/stat.h>       /* stat, S_IS* macros */
#include "rio.h"

#define PATH  "build/01_data.txt"
#define COPY  "build/01_copy.txt"

int main(void)
{
    const char *text =
        "line one\n"
        "line two\n"
        "line three\n";
    size_t textlen = strlen(text);

    /* ---- 1. the three descriptors you always have ------------------------ */
    printf("[fds] stdin=%d stdout=%d stderr=%d  (always open at startup)\n",
           STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO);

    /* ---- 2. create and write --------------------------------------------- */
    /* O_WRONLY: write only. O_CREAT: make it if missing. O_TRUNC: if it exists,
       throw away the old contents. 0644 = rw-r--r-- (the mode applies only when
       the file is actually created). */
    int fd = open(PATH, O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (fd < 0) { perror("open for write"); return 1; }
    printf("[open] '%s' for writing -> fd=%d  (lowest unused descriptor)\n",
           PATH, fd);

    if (rio_writen(fd, text, textlen) != (ssize_t)textlen) {
        perror("rio_writen"); return 1;
    }
    printf("[write] wrote %zu bytes\n", textlen);
    close(fd);

    /* ---- 3. ask the kernel about the file (metadata) --------------------- */
    struct stat st;
    if (stat(PATH, &st) < 0) { perror("stat"); return 1; }
    printf("[stat] size=%lld bytes  regular file=%s  dir=%s  mode=%o\n",
           (long long)st.st_size,
           S_ISREG(st.st_mode) ? "yes" : "no",
           S_ISDIR(st.st_mode) ? "yes" : "no",
           (unsigned)(st.st_mode & 0777));

    /* ---- 4. read it back ------------------------------------------------- */
    fd = open(PATH, O_RDONLY);
    if (fd < 0) { perror("open for read"); return 1; }

    char buf[64];
    ssize_t n = rio_readn(fd, buf, 8);      /* exactly 8 bytes */
    buf[n] = '\0';
    printf("[read] first 8 bytes: \"%s\"\n", buf);

    /* ---- 5. lseek: move the file position -------------------------------- */
    /* The descriptor carries a "current position". read/write advance it; lseek
       sets it. SEEK_SET = from the start, SEEK_CUR = relative, SEEK_END = from
       the end. Nothing is read or written by lseek itself. */
    off_t pos = lseek(fd, 0, SEEK_CUR);
    printf("[lseek] position after reading 8 bytes: %lld\n", (long long)pos);

    lseek(fd, 9, SEEK_SET);                 /* jump to the start of "line two" */
    n = rio_readn(fd, buf, 8);
    buf[n] = '\0';
    printf("[lseek] after seeking to byte 9, next 8 bytes: \"%s\"\n", buf);

    pos = lseek(fd, -6, SEEK_END);          /* 6 bytes before the end */
    n = rio_readn(fd, buf, 6);
    buf[n] = '\0';
    printf("[lseek] last 6 bytes (from offset %lld): \"%s\"\n",
           (long long)pos, buf);
    close(fd);

    /* ---- 6. copy the file, the robust way -------------------------------- */
    /* The canonical Unix copy loop: read a block, write exactly that many bytes,
       repeat until read returns 0 (EOF). rio_readn tolerates short counts. */
    int in  = open(PATH, O_RDONLY);
    int out = open(COPY, O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (in < 0 || out < 0) { perror("open for copy"); return 1; }

    char block[16];                 /* deliberately small, to loop several times */
    size_t total = 0;
    int    rounds = 0;
    while ((n = rio_readn(in, block, sizeof(block))) > 0) {
        if (rio_writen(out, block, (size_t)n) != n) { perror("write"); return 1; }
        total += (size_t)n;
        rounds++;
    }
    close(in); close(out);
    printf("[copy] copied %zu bytes in %d read/write rounds of %zu bytes\n",
           total, rounds, sizeof(block));

    stat(COPY, &st);
    printf("[copy] copy size matches original: %s\n",
           (size_t)st.st_size == textlen ? "yes" : "NO");

    printf("\nObservations\n------------\n");
    printf("- open() returned the LOWEST unused descriptor (3), because 0,1,2\n");
    printf("  are already taken by stdin/stdout/stderr.\n");
    printf("- read/write advance a position stored with the descriptor; lseek\n");
    printf("  moves it without transferring data (byte 9 began \"line two\").\n");
    printf("- stat() reports the kernel's metadata (size %zu, mode 0644), which\n", textlen);
    printf("  lives with the FILE, not with the descriptor.\n");
    printf("- the copy loop ran %d times for %zu bytes: read() returns what is\n",
           rounds, total);
    printf("  available, so a correct copy ALWAYS loops until EOF.\n");
    return 0;
}

/*
 * Observations (author's machine, Apple M4 Pro, macOS):
 *   [fds] stdin=0 stdout=1 stderr=2
 *   [open] 'build/01_data.txt' for writing -> fd=3
 *   [write] wrote 29 bytes
 *   [stat] size=29 bytes  regular file=yes  dir=no  mode=644
 *   [read] first 8 bytes: "line one"
 *   [lseek] position after reading 8 bytes: 8
 *   [lseek] after seeking to byte 9, next 8 bytes: "line two"
 *   [lseek] last 6 bytes (from offset 23): "three\n"
 *   [copy] copied 29 bytes in 2 read/write rounds of 16 bytes
 *   [copy] copy size matches original: yes
 *
 *   - fd=3 every time: descriptors are the lowest free slot in a per-process
 *     table whose first three entries are the standard streams.
 *   - The file is 29 bytes: "line one\n" (9) + "line two\n" (9) +
 *     "line three\n" (11). So byte 9 is the 'l' of "line two" (confirmed by the
 *     lseek read) and the last 6 bytes start at 29-6 = 23, giving "three\n".
 *   - A 29-byte file needed 2 rounds with a 16-byte buffer (16 + 13): the second
 *     read was SHORT because the file ended -- the normal, expected case that
 *     demo 02 explores when the short count is caused by timing instead.
 */
