#define _POSIX_C_SOURCE 200809L
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdio_ext.h>
#include <stdlib.h>
#include <string.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <unistd.h>

static void fail(const char *what) {
    perror(what);
    exit(2);
}

static void require(int ok, const char *what) {
    if (!ok) {
        fprintf(stderr, "check failed: %s\n", what);
        exit(2);
    }
}

static void command(char expected) {
    char got = 0;
    if (read(STDIN_FILENO, &got, 1) != 1) fail("command read");
    require(got == expected, "unexpected command");
}

static void event(const char *name, FILE *stream, int lockfd, int value) {
    struct stat data, lock;
    if (fstat(fileno(stream), &data) || fstat(lockfd, &lock)) fail("fstat");
    long position = ftell(stream);
    if (position < 0) fail("ftell");
    printf("{\"actor\":\"worker\",\"event\":\"%s\",\"pid\":%ld,"
           "\"data_dev\":%llu,\"data_ino\":%llu,\"lock_dev\":%llu,"
           "\"lock_ino\":%llu,\"position\":%ld,\"pending\":%zu,\"value\":%d}\n",
           name, (long)getpid(), (unsigned long long)data.st_dev,
           (unsigned long long)data.st_ino, (unsigned long long)lock.st_dev,
           (unsigned long long)lock.st_ino, position, __fpending(stream), value);
    if (fflush(stdout)) fail("event flush");
}

int main(int argc, char **argv) {
    require(argc == 4, "usage: probe DATA LOCK MODE");
    const char *mode = argv[3];
    int output = !strcmp(mode, "output-late") || !strcmp(mode, "output-early");
    require(output || !strcmp(mode, "input-retain") || !strcmp(mode, "input-seek")
            || !strcmp(mode, "input-flush") || !strcmp(mode, "input-reopen"), "mode");
    alarm(10);
    int lockfd = open(argv[2], O_RDWR);
    if (lockfd < 0) fail("open lock");
    if (flock(lockfd, LOCK_EX | LOCK_NB)) fail("initial flock");
    FILE *stream = fopen(argv[1], output ? "r+b" : "rb");
    if (!stream) fail("fopen");
    char buffer[4096];
    if (setvbuf(stream, buffer, _IOFBF, sizeof(buffer))) fail("setvbuf");
    if (fseek(stream, 0, SEEK_SET)) fail("initial fseek");
    require(fgetc(stream) == 'H', "header");
    if (output) {
        require(fgetc(stream) == '0', "initial counter");
        /* Required input-to-output transition on an update stream. */
        if (fseek(stream, 1, SEEK_SET)) fail("output fseek");
        require(fputc('1', stream) == '1', "buffered increment");
    }
    event("prepared", stream, lockfd, output ? 1 : -1);
    command('R');
    if (!strcmp(mode, "output-early")) {
        if (fflush(stream)) fail("early flush");
        event("flushed-before-unlock", stream, lockfd, 1);
    }
    if (flock(lockfd, LOCK_UN)) fail("first unlock");
    event("released", stream, lockfd, -1);
    command('C');
    if (output) {
        /* The late case deliberately transfers buffered output without exclusion. */
        if (fflush(stream)) fail("final flush");
        event("flushed-after-handoff", stream, lockfd, 1);
    } else {
        if (flock(lockfd, LOCK_EX | LOCK_NB)) fail("second flock");
        event("reacquired", stream, lockfd, -1);
        if (!strcmp(mode, "input-seek")) {
            if (fseek(stream, 1, SEEK_SET)) fail("second fseek");
        } else if (!strcmp(mode, "input-flush")) {
            if (fflush(stream)) fail("input flush");
        } else if (!strcmp(mode, "input-reopen")) {
            if (fclose(stream)) fail("close input");
            stream = fopen(argv[1], "rb");
            if (!stream) fail("reopen input");
            if (setvbuf(stream, buffer, _IOFBF, sizeof(buffer))) fail("reopen setvbuf");
            if (fseek(stream, 1, SEEK_SET)) fail("reopen seek");
        }
        int value = fgetc(stream);
        require(value >= '0' && value <= '9', "second input byte");
        event("observed", stream, lockfd, value - '0');
        command('U');
        if (flock(lockfd, LOCK_UN)) fail("second unlock");
        event("released-final", stream, lockfd, -1);
    }
    if (fclose(stream)) fail("fclose");
    if (close(lockfd)) fail("close lock");
    return 0;
}
