/**
 * 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.  This version includes more robust error checking.
 */

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

// Constants for different error codes we may return
static const int kWrongArgumentCount = 1;
static const int kSourceFileNonExistent = 2;
static const int kDestinationFileOpenFailure = 4;
static const int kReadFailure = 8;
static const int kWriteFailure = 16;
static const int kFileCloseFailure = 32;

// 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.
 */
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);

        // optional error checking
        if (count == -1) {
            error(kWriteFailure, 0, "lost access to file while writing.");
        }

        bytesWritten += count;
    }
}

/* This function copies the contents of the source file into each destination
 * file in chunks until the entire file is copied.  If an error occurs
 * while reading or writing, this function throws an error.
 */
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;

        // optional error checking
        if (bytesRead == -1) {
            error(kReadFailure, 0, "lost access to file while reading.");
        }

        writeAllBytes(destinationFD, buffer, bytesRead);
    }
}

int main(int argc, char *argv[]) {
    // Ensure the user specified 3 arguments
    if (argc != 3) {
        error(kWrongArgumentCount, 0, "%s <source-file> <destination-file>.", argv[0]);
    }

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

    // Optional error checking
    if (sourceFD == -1) {
        error(kSourceFileNonExistent, 0, "%s: source file could not be opened.", argv[1]);
    }

    // Open the specified destination file for writing, creating if nonexistent
    int destinationFD = open(argv[2], O_WRONLY | O_CREAT | O_EXCL, kDefaultPermissions);

    // Optional error checking
    if (destinationFD == -1) {
        error(kDestinationFileOpenFailure, 0, "%s: destination file could not be created.", argv[2]);
    }

    copyContents(sourceFD, destinationFD);

    // Close the source file (optional error checking)
    if (close(sourceFD) == -1) {
        error(kFileCloseFailure, 0, "%s: had trouble closing file.", argv[1]);
    }

    // Close the destination file (optional error checking)
    if (close(destinationFD) == -1) {
        error(kFileCloseFailure, 0, "%s: had trouble closing file.", argv[2]);
    }

    return 0;
}
