#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/statfs.h>
#include <sys/utsname.h>
#include <unistd.h>

static void operation(const char *name, int fd, int command, uint64_t value, int last)
{
    errno = 0;
    int result = fcntl(fd, command, &value);
    int error = result < 0 ? errno : 0;
    printf("    {\"operation\":\"%s\",\"rc\":%d,\"errno\":%d,\"value\":%" PRIu64 "}%s\n",
           name, result, error, value, last ? "" : ",");
}

int main(int argc, char **argv)
{
    if (argc != 2) {
        fprintf(stderr, "Usage: %s scratch-directory\n", argv[0]);
        return 2;
    }
    char *path = NULL;
    if (asprintf(&path, "%s/write-hint-XXXXXX", argv[1]) < 0) return 1;
    int first = mkstemp(path);
    if (first < 0) { perror("mkstemp"); free(path); return 1; }
    int second = open(path, O_RDWR | O_CLOEXEC);
    if (second < 0) {
        perror("open"); unlink(path); close(first); free(path); return 1;
    }
    if (unlink(path) != 0) {
        perror("unlink"); close(second); close(first); free(path); return 1;
    }
    free(path);
    struct utsname system;
    struct statfs filesystem;
    if (uname(&system) != 0 || fstatfs(first, &filesystem) != 0) {
        perror("environment"); close(second); close(first); return 1;
    }
    printf("{\n  \"schemaVersion\":1,\n  \"kernel\":\"%s\",\n"
           "  \"machine\":\"%s\",\n  \"filesystemType\":\"0x%lx\",\n"
           "  \"scope\":\"fcntl return values and stored hints only; no data writes or NAND observation\",\n"
           "  \"observations\":[\n",
           system.release, system.machine, (unsigned long)filesystem.f_type);
    operation("initial_inode", first, F_GET_RW_HINT, 0, 0);
    operation("set_short_first", first, F_SET_RW_HINT, RWH_WRITE_LIFE_SHORT, 0);
    operation("get_second", second, F_GET_RW_HINT, 0, 0);
    operation("set_long_second", second, F_SET_RW_HINT, RWH_WRITE_LIFE_LONG, 0);
    operation("get_first", first, F_GET_RW_HINT, 0, 0);
    operation("set_invalid", first, F_SET_RW_HINT, 255, 0);
    operation("after_invalid", first, F_GET_RW_HINT, 0, 0);
    operation("get_file_hint", first, F_GET_FILE_RW_HINT, 0, 0);
    operation("set_file_hint", first, F_SET_FILE_RW_HINT, RWH_WRITE_LIFE_SHORT, 1);
    printf("  ]\n}\n");
    int failed = close(second) != 0;
    failed |= close(first) != 0;
    return failed;
}
