/**
 * File: copy.c
 * --------------
 * This program is the starter code for an example that shows how we can
 * make a copy of a specified file into another specified file, similar to the
 * `cp` unix command.
 */

#include <fcntl.h>
#include <stdbool.h>
#include <stdio.h>
#include <unistd.h>

// The permissions to set if the destination file doesn't exist
static const int kDefaultPermissions = 0644;  // number equivalent of "rw-r--r--"

// The number of bytes we copy at once from source to destination
static const int kCopyIncrement = 1024;

/* This is a helper function wrapper around `write` that guarantees the first
 * nbytes bytes in buffer will be written to destinationFD (unless write
 * encounters an error and returns -1 - in this implementation, this is
 * assumed not to happen, but full error checking is implemented in
 * copy-soln-full.c).
 */
void writeAllBytes(int destinationFD, char buffer[], size_t nbytes) {
    size_t bytesWritten = 0;
    while (bytesWritten < nbytes) {
        ssize_t count = write(destinationFD, buffer + bytesWritten, nbytes - bytesWritten);

        // write error checking omitted (see copy-soln-full.c for added error checking)

        bytesWritten += count;
    }
}

/* This function copies the contents of the source file into the destination
 * file in chunks until the entire file is copied.
 */
void copyContents(int sourceFD, int destinationFD) {
    while (true) {
        char buffer[kCopyIncrement];

        // Read the next chunk of bytes from the source
        ssize_t bytesRead = read(sourceFD, buffer, sizeof(buffer));

        // check if we are at the end of the file
        if (bytesRead == 0) break;

        // read error checking omitted (see copy-soln-full.c for added error checking)

        writeAllBytes(destinationFD, buffer, bytesRead);
    }
}

int main(int argc, char *argv[]) {
    // Open the specified source file for reading
    int sourceFD = open(argv[1], O_RDONLY);

    // open error checking omitted (see copy-soln-full.c for added error checking)

    // Open the specified destination file for writing, creating if nonexistent
    int destinationFD = open(argv[2], O_WRONLY | O_CREAT | O_EXCL, kDefaultPermissions);
    if (destinationFD == -1) {
        // Can also use the error function for cleaner error checking - see copy-soln-full.c.
        printf("%s: destination file could not be created.\n", argv[2]);
        return 1;
    }

    copyContents(sourceFD, destinationFD);

    // Close the source and destination files (see copy-soln-full.c for added error checking)
    close(sourceFD);
    close(destinationFD);

    return 0;
}
