#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>

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

static int request(int fd, const char *api, int release) {
    if (!strcmp(api, "flock"))
        return flock(fd, release ? LOCK_UN : LOCK_EX | LOCK_NB);
    struct flock lock = { .l_type = release ? F_UNLCK : F_WRLCK,
        .l_whence = SEEK_SET, .l_start = 0, .l_len = 1, .l_pid = 0 };
    if (!strcmp(api, "posix")) return fcntl(fd, F_SETLK, &lock);
    if (!strcmp(api, "ofd")) return fcntl(fd, F_OFD_SETLK, &lock);
    errno = EINVAL;
    return -1;
}

static void contender(int holder, const char *path, const char *api,
                      const char *phase, const struct stat *identity) {
    pid_t child = fork();
    if (child == -1) fail("fork");
    if (child == 0) {
        /* Drop the inherited description before obtaining an independent owner. */
        if (close(holder)) fail("child close");
        int fd = open(path, O_RDWR | O_CLOEXEC);
        if (fd == -1) fail("child open");
        struct stat observed;
        if (fstat(fd, &observed)) fail("child fstat");
        if (observed.st_dev != identity->st_dev || observed.st_ino != identity->st_ino) {
            fprintf(stderr, "file identity changed\n");
            exit(2);
        }
        errno = 0;
        int rc = request(fd, api, 0);
        int error = rc == 0 ? 0 : errno;
        if (rc && error != EAGAIN && error != EACCES) fail("unexpected lock error");
        printf("{\"phase\":\"%s\",\"acquired\":%s,\"errno\":%d,\"same_file\":true}\n",
               phase, rc == 0 ? "true" : "false", error);
        if (fflush(stdout)) fail("flush");
        if (close(fd)) fail("child cleanup");
        _exit(0);
    }
    int status;
    if (waitpid(child, &status, 0) != child) fail("waitpid");
    if (!WIFEXITED(status) || WEXITSTATUS(status)) {
        fprintf(stderr, "contender failed\n");
        exit(2);
    }
}

int main(int argc, char **argv) {
    if (argc != 4) {
        fprintf(stderr, "usage: probe FILE HOLDER_API CONTENDER_API\n");
        return 2;
    }
    int holder = open(argv[1], O_RDWR | O_CLOEXEC);
    if (holder == -1) fail("holder open");
    struct stat identity;
    if (fstat(holder, &identity)) fail("holder fstat");
    if (request(holder, argv[2], 0)) fail("holder lock");
    contender(holder, argv[1], argv[3], "held", &identity);
    if (request(holder, argv[2], 1)) fail("holder unlock");
    contender(holder, argv[1], argv[3], "released", &identity);
    if (close(holder)) fail("holder close");
    return 0;
}
