#include <stdint.h>
#include <stdlib.h>
#include <string.h>

#include "fs_private.h"

void FS_Copyfiles(char *sourceOSPath, char *destOSPath)
{
    FILE *file;
    int32_t fileLength;
    void *buffer;
    size_t transferCount;

    if (strstr(sourceOSPath, "journal.dat") != NULL) {
        return;
    }

    if (strstr(sourceOSPath, "journaldata.dat") != NULL) {
        return;
    }

    file = fopen(sourceOSPath, "rb");
    if (file == NULL) {
        return;
    }

    fseek(file, 0, SEEK_END);
    fileLength = (int32_t)ftell(file);
    fseek(file, 0, SEEK_SET);

    /* ORIGINAL_BINARY_BUG: stock uses this unchecked raw allocation as the
     * destination of the following full-size read; see
     * original-bugs/coduomp-copyfiles-unchecked-allocation.md. */
    buffer = malloc((size_t)(uint32_t)fileLength);
    transferCount =
        fread(buffer, 1, (size_t)(uint32_t)fileLength, file);
    if (transferCount != (size_t)(uint32_t)fileLength) {
        Com_Error(0, "\x15" "Short read in FS_Copyfiles()\n");
    }

    fclose(file);

    if (FS_CreatePath(destOSPath) != 0) {
        free(buffer);
        return;
    }

    file = fopen(destOSPath, "wb");
    if (file == NULL) {
        free(buffer);
        return;
    }

    transferCount =
        fwrite(buffer, 1, (size_t)(uint32_t)fileLength, file);
    if (transferCount != (size_t)(uint32_t)fileLength) {
        Com_Error(0, "\x15" "Short write in FS_Copyfiles()\n");
    }

    fclose(file);
    free(buffer);
}
