/* Original Hesela observation, CC0-1.0. Only newly created temporary files. */
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <linux/fiemap.h>
#include <linux/fs.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <unistd.h>

#define LENGTH (1024 * 1024)
#define EXTENTS 256

static void fail(const char *operation) {
    perror(operation);
    exit(EXIT_FAILURE);
}

static unsigned char pattern(size_t offset) {
    return (unsigned char)(offset % 251 + 1);
}

static void observe(int fd, const char *stage, unsigned flags, int comma) {
    struct stat before, after;
    struct fiemap *map = calloc(1, sizeof(*map) + EXTENTS * sizeof(struct fiemap_extent));
    if (!map) fail("calloc");
    map->fm_length = LENGTH;
    map->fm_extent_count = EXTENTS;
    map->fm_flags = flags;
    if (fstat(fd, &before)) fail("fstat before");
    if (ioctl(fd, FS_IOC_FIEMAP, map)) fail("FIEMAP");
    if (fstat(fd, &after)) fail("fstat after");
    if (map->fm_mapped_extents == EXTENTS &&
        !(map->fm_extents[EXTENTS - 1].fe_flags & FIEMAP_EXTENT_LAST)) {
        fprintf(stderr, "incomplete extent mapping\n");
        exit(1);
    }
    printf("%s{\"stage\":\"%s\",\"requestFlags\":%u,\"returnedFlags\":%u,"
           "\"logicalBytes\":%jd,\"blocks512Before\":%jd,\"blocks512After\":%jd,"
           "\"extents\":[",
           comma ? "," : "", stage, flags, map->fm_flags, (intmax_t)after.st_size,
           (intmax_t)before.st_blocks, (intmax_t)after.st_blocks);
    for (unsigned i = 0; i < map->fm_mapped_extents; i++) {
        const struct fiemap_extent *e = &map->fm_extents[i];
        printf("%s{\"logicalBytes\":%ju,\"lengthBytes\":%ju,\"flags\":%u}",
               i ? "," : "", (uintmax_t)e->fe_logical, (uintmax_t)e->fe_length, e->fe_flags);
    }
    printf("]}");
    free(map);
}

int main(int argc, char **argv) {
    if (argc != 2 || (strcmp(argv[1], "control") && strcmp(argv[1], "fsync") &&
                      strcmp(argv[1], "fiemap-sync"))) {
        fprintf(stderr, "usage: observe control|fsync|fiemap-sync\n");
        return 2;
    }
    char path[] = "fiemap-XXXXXX";
    int fd = mkstemp(path);
    if (fd < 0) fail("mkstemp");
    if (unlink(path)) fail("unlink");
    unsigned char buffer[8192];
    size_t offset = 0;
    while (offset < LENGTH) {
        for (size_t i = 0; i < sizeof(buffer); i++) buffer[i] = pattern(offset + i);
        size_t remaining = LENGTH - offset;
        size_t wanted = remaining < sizeof(buffer) ? remaining : sizeof(buffer);
        ssize_t count = pwrite(fd, buffer, wanted, (off_t)offset);
        if (count < 0 && errno == EINTR) continue;
        if (count < 0) fail("pwrite");
        if (!count) { fprintf(stderr, "zero-length write\n"); return 1; }
        offset += (size_t)count;
    }
    printf("{\"arm\":\"%s\",\"observations\":[", argv[1]);
    observe(fd, "before", 0, 0);
    if (!strcmp(argv[1], "fsync") && fsync(fd)) fail("fsync");
    observe(fd, "after", !strcmp(argv[1], "fiemap-sync") ? FIEMAP_FLAG_SYNC : 0, 1);
    /* Readback follows both mappings, so it cannot affect the earlier snapshots. */
    size_t read_bytes = 0, mismatches = 0;
    while (read_bytes < LENGTH) {
        size_t remaining = LENGTH - read_bytes;
        size_t wanted = remaining < sizeof(buffer) ? remaining : sizeof(buffer);
        ssize_t count = pread(fd, buffer, wanted, (off_t)read_bytes);
        if (count < 0 && errno == EINTR) continue;
        if (count < 0) fail("pread");
        if (!count) { fprintf(stderr, "unexpected EOF\n"); return 1; }
        for (ssize_t i = 0; i < count; i++)
            mismatches += buffer[i] != pattern(read_bytes + (size_t)i);
        read_bytes += (size_t)count;
    }
    printf("],\"bytesRead\":%zu,\"mismatchedBytes\":%zu}\n", read_bytes, mismatches);
    if (close(fd)) fail("close");
    return mismatches ? 1 : 0;
}
