Skip to content
pi-c Documentation
Login

Documentation

/* Scripted provider. The reply for a turn depends only on the script and the
 * turn number, so a restarted process asks for, and gets, the same reply. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "pic.h"

#define PIC_SCRIPT_LINE_CAP 8192

static char *dup_string(const char *s) {
    size_t n = strlen(s) + 1;
    char *p = malloc(n);
    if (p) {
        memcpy(p, s, n);
    }
    return p;
}

void pic_reply_free(pic_reply *r) {
    free(r->tool);
    free(r->args);
    memset(r, 0, sizeof *r);
}

/* Lines: "text ANSWER", "tool write NAME TEXT", "tool exec COMMAND". */
static int parse(char *line, pic_reply *out, char *err, size_t errcap) {
    line[strcspn(line, "\n")] = '\0';
    if (strncmp(line, "text ", 5) == 0) {
        out->kind = PIC_REPLY_TEXT;
        out->args = dup_string(line + 5);
        return out->args ? 0 : -1;
    }
    if (strncmp(line, "tool ", 5) == 0) {
        char *name = line + 5;
        char *space = strchr(name, ' ');
        if (!space) {
            (void)snprintf(err, errcap, "script tool line has no arguments");
            return -1;
        }
        *space = '\0';
        out->kind = PIC_REPLY_TOOL;
        out->tool = dup_string(name);
        out->args = dup_string(space + 1);
        return out->tool && out->args ? 0 : -1;
    }
    (void)snprintf(err, errcap, "unrecognized script line: %.60s", line);
    return -1;
}

int pic_provider_reply(const char *script, int64_t turn, pic_reply *out, char *err, size_t errcap) {
    char line[PIC_SCRIPT_LINE_CAP];
    FILE *f = fopen(script, "r");
    int64_t index = 0;
    int rc = -1;
    memset(out, 0, sizeof *out);
    if (!f) {
        (void)snprintf(err, errcap, "cannot open script %s", script);
        return -1;
    }
    while (fgets(line, sizeof line, f)) {
        if (index++ == turn) {
            rc = parse(line, out, err, errcap);
            break;
        }
    }
    if (index <= turn) {
        (void)snprintf(err, errcap, "script has no reply for turn %lld", (long long)turn);
    }
    fclose(f);
    if (rc != 0) {
        pic_reply_free(out);
    }
    return rc;
}