#define _POSIX_C_SOURCE 200809L
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

#define INPUT "worker-input.txt"
#define INPUT_SIZE 10000

/* The function we will probe: its cost depends on id % 5. */
__attribute__((noinline)) int process_item(int id) {
    volatile unsigned long x = 0;
    for (int i = 0; i < (id % 5 + 1) * 200000; i++)
        x += (unsigned long)i;
    return id % 7;
}

static int make_input(void) {
    char data[INPUT_SIZE];
    memset(data, 'x', sizeof data);
    int fd = open(INPUT, O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (fd < 0) return -1;
    ssize_t w = write(fd, data, sizeof data);
    close(fd);
    return w == (ssize_t)sizeof data ? 0 : -1;
}

/* Reads the input in 4096-byte chunks: 4096 + 4096 + 1808, then 0 (EOF). */
static long read_input(void) {
    char buf[4096];
    long total = 0;
    ssize_t r;
    int fd = open(INPUT, O_RDONLY);
    if (fd < 0) return -1;
    while ((r = read(fd, buf, sizeof buf)) > 0)
        total += r;
    close(fd);
    return total;
}

int main(int argc, char **argv) {
    int items = argc > 1 ? atoi(argv[1]) : 50;
    long result_sum = 0;
    if (items <= 0 || make_input() != 0) {
        fprintf(stderr, "usage: %s [items>0] (run in a writable directory)\n", argv[0]);
        return 2;
    }
    for (int i = 0; i < items; i++) {
        if (i % 10 == 0) {
            /* An optional file that never exists: this open fails with ENOENT. */
            int fd = open("missing.conf", O_RDONLY);
            if (fd >= 0) close(fd);
            else if (errno != ENOENT) perror("missing.conf");
        }
        if (read_input() != INPUT_SIZE) {
            fprintf(stderr, "short read on %s\n", INPUT);
            return 1;
        }
        result_sum += process_item(i);
        struct timespec pause = { 0, 2 * 1000 * 1000 }; /* 2 ms */
        nanosleep(&pause, NULL);
    }
    printf("items=%d result_sum=%ld pid=%ld\n", items, result_sum, (long)getpid());
    return 0;
}
