/*
 * signet-api: FastCGI backend (kcgi, run under kfcgi).
 *
 *   GET  /me
 *   POST /me/facsimile              label, file=<png> (new immutable variant)
 *   POST /me/facsimile/default      facsimile_id=<uuid>
 *   POST /me/facsimile/retry        facsimile_id=<uuid> (idempotent activation)
 *   POST /facsimiles                user, label, file=<png> (admin)
 *   GET  /docs?scope=mine|pending|involved|all
 *   POST /docs                      file=<pdf> | template_id=<uuid>
 *   GET  /docs/<id>
 *   POST /docs/<id>/save            json={title,series_code,layout,route}
 *   POST /docs/<id>/submit
 *   POST /docs/<id>/rerender
 *   POST /docs/<id>/decide          decision, comment, placement, facsimile_id
 *   POST /docs/<id>/delete          (drafts only)
 *   GET  /docs/<id>/file/<source|proof|stamped|final>
 *   GET  /templates     POST /templates   doc_id, name
 *   GET  /series        POST /series      code, pattern
 *   GET  /pim           GET  /dam
 *
 * Identity comes from the deployment's trusted auth proxy as headers; roles are
 * mapped from groups in signet.conf.  Nothing here ever reads sig_dir.
 */
#include <sys/stat.h>

#include <dirent.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>

#include "conf.h"
#include "db.h"
#include "http.h"
#include "render.h"
#include "snapshot.h"
#include "upload.h"
#include "util.h"

static struct conf cf;

/* Bound parse/clone work independently of the PDF upload limit. */
#define MAX_JSON_BYTES (1024u * 1024)
#define PENDING "('PENDING')"
#define IN_ROUTE(u) "EXISTS (SELECT 1 FROM jsonb_array_elements(d.route_json->'parties') p " \
	"WHERE p->>'signer' = " u ")"
#define ROUTE_ACCESS(u) "(d.status NOT IN ('DRAFT','CORRECTION_REQUIRED') AND " \
	"EXISTS (SELECT 1 FROM jsonb_array_elements(d.route_json->'parties') " \
	"WITH ORDINALITY p(party, n) WHERE p.party->>'signer' = " u \
	" AND p.n <= d.current_party))"
#define CAN_DECIDE(u) "(d.status IN " PENDING " AND d.rendered_seq = d.render_seq " \
	"AND d.render_error IS NULL " \
	"AND (d.route_json->'parties'->(d.current_party - 1)->>'signer') = " u \
	" AND NOT EXISTS (SELECT 1 FROM doc_decisions x WHERE x.doc_id = d.id " \
	"AND x.revision = d.revision AND x.party = d.current_party))"

static void
doc_path(char *buf, size_t sz, const char *id, const char *name)
{
	snprintf(buf, sz, "%s/docs/%s%s%s", conf_get(&cf, "data_dir",
	    "/var/lib/signet"), id, name ? "/" : "", name ? name : "");
}

static int
log_event(PGconn *pg, const char *id, const char *actor, const char *action,
    const char *detail)
{
	const char *p[] = { id, actor, action, detail };

	return db_do(pg, "INSERT INTO doc_events (doc_id, actor, action, detail) "
	    "VALUES ($1, $2, $3, $4)", 4, p);
}

/* Send the single text column of a one-row result as the JSON body. */
static void
send_sql_json(struct kreq *r, PGconn *pg, const char *sql, int n,
    const char *const *params)
{
	PGresult *res = db_q(pg, sql, n, params);

	if (res == NULL)
		send_err(r, KHTTP_500, "database error");
	else if (PQntuples(res) != 1 || PQgetisnull(res, 0, 0))
		send_err(r, KHTTP_404, "not found");
	else
		send_json(r, KHTTP_200, PQgetvalue(res, 0, 0));
	if (res != NULL)
		PQclear(res);
}

static int
enqueue(const char *id, const char *revision, const char *seq, const char *kind)
{
	redisContext *rc = redis_get(&cf);
	redisReply *rep;
	char job[192];
	int ok;

	if (rc == NULL)
		return -1;
	snprintf(job, sizeof(job), "{\"doc_id\":\"%s\",\"revision\":%d,"
	    "\"seq\":%d,\"kind\":\"%s\"}", id, atoi(revision), atoi(seq), kind);
	rep = redisCommand(rc, "LPUSH %s %s", conf_get(&cf, "queue",
	    "queue:stamping"), job);
	ok = rep != NULL && rep->type == REDIS_REPLY_INTEGER;
	if (rep != NULL)
		freeReplyObject(rep);
	return ok ? 0 : -1;
}

/* --- validation ------------------------------------------------------------ */

static const char *
check_layout(yyjson_val *layout)
{
	static const char *types[] = { "pim_text", "pim_image", "date", "serial",
	    "signature_zone", NULL };
	yyjson_val *imps, *imp, *v;
	size_t i, max, j, jmax;
	const char *type, *ref, *font, *party;
	int k;
	double x, y, w, h, min_w, min_h;

	if (!yyjson_is_obj(layout))
		return "layout must be an object";
	imps = yyjson_obj_get(layout, "imprints");
	if (imps == NULL)
		return NULL;
	if (!yyjson_is_arr(imps) || yyjson_arr_size(imps) > 200)
		return "imprints must be an array of at most 200 items";
	yyjson_arr_foreach(imps, i, max, imp) {
		type = yyjson_get_str(yyjson_obj_get(imp, "type"));
		ref = yyjson_get_str(yyjson_obj_get(imp, "ref"));
		font = yyjson_get_str(yyjson_obj_get(imp, "font"));
		for (k = 0; type != NULL && types[k] != NULL; k++)
			if (strcmp(types[k], type) == 0)
				break;
		if (type == NULL || types[k] == NULL)
			return "unknown imprint type";
		v = yyjson_obj_get(imp, "coords");
		if (!yyjson_is_arr(v) || yyjson_arr_size(v) < 3 ||
		    yyjson_arr_size(v) > 64)
			return "bad imprint coords";
		yyjson_arr_foreach(v, j, jmax, v)
			if (!yyjson_is_num(v))
				return "bad imprint coords";
		if ((strcmp(type, "pim_text") == 0 || strcmp(type, "pim_image") == 0) &&
		    (ref == NULL || !*ref || !is_safe_name(ref)))
			return "PIM imprints need a key";
		if (strcmp(type, "signature_zone") == 0) {
			party = yyjson_get_str(yyjson_obj_get(imp, "party"));
			if (party == NULL || !*party || !is_safe_name(party))
				return "signature_zone needs a party name";
			v = yyjson_obj_get(imp, "coords");
			if (!yyjson_is_arr(v) || yyjson_arr_size(v) != 4)
				return "signature_zone coords must be [x1, y1, x2, y2]";
			if (!yyjson_is_num(yyjson_arr_get(v, 0)) ||
			    !yyjson_is_num(yyjson_arr_get(v, 1)) ||
			    !yyjson_is_num(yyjson_arr_get(v, 2)) ||
			    !yyjson_is_num(yyjson_arr_get(v, 3)))
				return "signature_zone coords must be numbers";
			x = yyjson_get_num(yyjson_arr_get(v, 0));
			y = yyjson_get_num(yyjson_arr_get(v, 1));
			w = yyjson_get_num(yyjson_arr_get(v, 2)) - x;
			h = yyjson_get_num(yyjson_arr_get(v, 3)) - y;
			double rw = yyjson_get_num(yyjson_obj_get(imp, "ref_w"));
			double rh = yyjson_get_num(yyjson_obj_get(imp, "ref_h"));
			if (yyjson_obj_get(imp, "ref_w") == NULL)
				rw = yyjson_get_num(yyjson_obj_get(layout, "reference_width"));
			if (yyjson_obj_get(imp, "ref_h") == NULL)
				rh = yyjson_get_num(yyjson_obj_get(layout, "reference_height"));
			v = yyjson_obj_get(imp, "page");
			const char *shape = yyjson_get_str(yyjson_obj_get(imp, "shape"));
			if (!yyjson_is_int(v) || yyjson_get_sint(v) < 1 || yyjson_get_sint(v) > 500 ||
			    (shape != NULL && strcmp(shape, "rect") != 0) ||
			    !isfinite(rw) || !isfinite(rh) || rw <= 0 || rh <= 0 ||
			    !isfinite(x) || !isfinite(y) || !isfinite(w) || !isfinite(h) ||
			    x < 0 || y < 0 || w <= 0 || h <= 0 || x + w > rw || y + h > rh)
				return "signature_zone needs a valid page, reference size and rectangle";
			v = yyjson_obj_get(imp, "min_w");
			min_w = yyjson_is_num(v) ? yyjson_get_num(v) : 0;
			v = yyjson_obj_get(imp, "min_h");
			min_h = yyjson_is_num(v) ? yyjson_get_num(v) : 0;
			if (!isfinite(min_w) || !isfinite(min_h) || min_w <= 0 || min_h <= 0 ||
			    min_w > w || min_h > h)
				return "signature_zone minimum dimensions must be positive and fit the zone";
		}
		if (font != NULL && *font && !is_safe_relpath(font))
			return "bad font reference";
	}
	return NULL;
}

static const char *
check_route(yyjson_val *route)
{
	yyjson_val *parties = yyjson_obj_get(route, "parties"), *p;
	const char *name, *signer;
	size_t i, max;

	if (!yyjson_is_arr(parties) || yyjson_arr_size(parties) > 20)
		return "route.parties must be an array of at most 20 parties";
	yyjson_arr_foreach(parties, i, max, p) {
		if (!yyjson_is_obj(p))
			return "each party must be an object";
		name = yyjson_get_str(yyjson_obj_get(p, "name"));
		if (name == NULL || !*name || !is_safe_name(name) || strlen(name) > 20)
			return "party name must be 1–20 safe characters";
		signer = yyjson_get_str(yyjson_obj_get(p, "signer"));
		if (signer != NULL && (!*signer || !is_safe_name(signer)))
			return "party signer must be a safe name";
		for (size_t j = 0; j < i; j++)
			if (strcmp(name, yyjson_get_str(yyjson_obj_get(yyjson_arr_get(parties, j), "name"))) == 0)
				return "party names must be unique";
	}
	return NULL;
}

static const char *
check_zones(yyjson_val *layout, yyjson_val *route)
{
	yyjson_val *imp, *party, *parties = yyjson_obj_get(route, "parties");
	size_t i, n, j, count;
	char seen[20] = {0};

	yyjson_arr_foreach(yyjson_obj_get(layout, "imprints"), i, n, imp) {
		const char *type = yyjson_get_str(yyjson_obj_get(imp, "type"));
		if (strcmp(type, "signature_zone") != 0)
			continue;
		const char *name = yyjson_get_str(yyjson_obj_get(imp, "party"));
		yyjson_arr_foreach(parties, j, count, party)
			if (strcmp(name, yyjson_get_str(yyjson_obj_get(party, "name"))) == 0)
				break;
		if (j == yyjson_arr_size(parties))
			return "signature zone references an unknown party";
		if (seen[j]++)
			return "a party can have only one signature zone";
	}
	return NULL;
}

/* Everything the worker would trip over is checked before we accept a submit. */
static int
check_submittable(yyjson_val *layout, yyjson_val *route, const char *org_code,
    int has_series, char *err, size_t errsz)
{
	yyjson_val *imp;
	size_t i, max;
	const char *type, *msg;

	if ((msg = check_layout(layout)) != NULL || (msg = check_route(route)) != NULL ||
	    (msg = check_zones(layout, route)) != NULL) {
		snprintf(err, errsz, "%s", msg);
		return -1;
	}
	yyjson_val *parties = yyjson_obj_get(route, "parties");
	if (yyjson_arr_size(parties) < 1) {
		snprintf(err, errsz, "Define at least one party to sign this document");
		return -1;
	}
	yyjson_arr_foreach(parties, i, max, imp) {
		const char *party_name = yyjson_get_str(yyjson_obj_get(imp, "name"));
		const char *party_signer = yyjson_get_str(yyjson_obj_get(imp, "signer"));
		if (party_signer == NULL || !*party_signer) {
			snprintf(err, errsz, "Party '%s' does not have a signer assigned", party_name ? party_name : "(unnamed)");
			return -1;
		}
	}

	/* validate imprints */
	yyjson_val *imprints = yyjson_obj_get(layout, "imprints");
	yyjson_arr_foreach(imprints, i, max, imp) {
		type = yyjson_get_str(yyjson_obj_get(imp, "type"));
		if ((strcmp(type, "pim_text") == 0 || strcmp(type, "pim_image") == 0) &&
		    (org_code == NULL || !*org_code)) {
			snprintf(err, errsz, "Select an organisation for PIM imprints");
			return -1;
		}
		/* Attribute existence and bytes are checked once, by snapshot_create. */
		if (strcmp(type, "serial") == 0 && !has_series) {
			snprintf(err, errsz, "Serial number field is used, but no series is selected — choose a series or remove the serial field");
			return -1;
		}
	}
	return 0;
}

/* --- handlers -------------------------------------------------------------- */

static void
h_me(struct kreq *r, PGconn *pg, const struct ident *id)
{
	const char *p[] = { id->user,
	    ident_has_role(id, &cf, "drafter") ? "true" : "false",
	    ident_has_role(id, &cf, "signer") ? "true" : "false",
	    ident_has_role(id, &cf, "admin") ? "true" : "false" };

	/* Metadata only: original images never pass through the API. */
	send_sql_json(r, pg, "SELECT json_build_object('user', $1::varchar, 'roles', "
	    "json_build_object('drafter',$2::boolean,'signer',$3::boolean,'admin',$4::boolean), "
	    "'enrolled', EXISTS(SELECT 1 FROM facsimiles WHERE username=$1 AND is_default AND enrolled_at IS NOT NULL), "
	    "'facsimile', coalesce((SELECT json_build_object('id',id,'label',label,'width',width,'height',height) "
	    "FROM facsimiles WHERE username=$1 AND is_default AND enrolled_at IS NOT NULL), "
	    "json_build_object('width',0,'height',0)), "
	    "'facsimiles', (SELECT coalesce(json_agg(f), '[]') FROM (SELECT id,label,is_default,width,height, "
	    "enrolled_at IS NOT NULL AS enrolled,enrol_error AS error FROM facsimiles WHERE username=$1 "
	    "ORDER BY (enrol_error IS NULL) DESC, created_at DESC,id DESC LIMIT 64) f))::text", 4, p);
}

static void
h_docs_list(struct kreq *r, PGconn *pg, const struct ident *id)
{
	const char *scope = http_field_str(r, "scope"), *where;
	const char *p[] = { id->user };
	char sql[2048];

	if (scope == NULL)
		scope = "mine";
	if (strcmp(scope, "pending") == 0)
		where = CAN_DECIDE("$1");
	else if (strcmp(scope, "involved") == 0)
		where = ROUTE_ACCESS("$1");
	else if (strcmp(scope, "all") == 0 && ident_has_role(id, &cf, "admin"))
		where = "$1 <> ''";
	else
		where = "d.drafter_user = $1";
	snprintf(sql, sizeof(sql),
	    "SELECT coalesce(json_agg(t), '[]')::text FROM ("
	    "SELECT d.id, d.status, d.title, d.serial, d.drafter_user, "
	    "d.revision, d.current_party, coalesce(d.source_received<d.source_total,false) AS uploading, "
	    "jsonb_array_length(d.route_json->'parties') AS parties, "
	    "d.created_at, d.submitted_at, d.released_at "
	    "FROM documents d WHERE %s ORDER BY d.created_at DESC LIMIT 200) t", where);
	send_sql_json(r, pg, sql, 1, p);
}

static int
upload_number(const char *s, size_t *n)
{
	if (s == NULL || *s == '\0' || strlen(s) > 8 ||
	    strspn(s, "0123456789") != strlen(s))
		return -1;
	*n = strtoul(s, NULL, 10);
	return *n <= UPLOAD_MAX_BYTES ? 0 : -1;
}

static void
h_doc_create(struct kreq *r, PGconn *pg, const struct ident *id)
{
	struct kpair *file = http_field(r, "file");
	const char *tpl = http_field_str(r, "template_id");
	const char *declared = http_field_str(r, "total_size");
	const char *p[4] = { id->user, tpl, NULL, NULL }, *docid;
	char dir[600], path[700], src[700], body[200], err[256];
	char total_buf[32], received_buf[32];
	size_t total = 0;
	int chunked = http_field(r, "total_size") != NULL;
	PGresult *res;

	if (!ident_has_role(id, &cf, "drafter")) {
		send_err(r, KHTTP_403, "drafter role required");
		return;
	}
	if (chunked && (upload_number(declared, &total) == -1 || file == NULL ||
	    file->valsz > UPLOAD_CHUNK_BYTES || total < file->valsz || (tpl != NULL && *tpl))) {
		send_err(r, KHTTP_400, "PDF total must fit within 32 MiB; chunks within 256 KiB");
		return;
	}
	if (db_do(pg, "BEGIN", 0, NULL) == -1) {
		send_err(r, KHTTP_500, "database error");
		return;
	}
	if (tpl != NULL && *tpl) {
		if (!is_uuid(tpl)) {
			db_do(pg, "ROLLBACK", 0, NULL);
			send_err(r, KHTTP_400, "bad template_id");
			return;
		}
		res = db_q(pg, "INSERT INTO documents (drafter_user, template_id, "
		    "series_code, layout_json, route_json) SELECT $1::varchar, t.id, "
		    "t.series_code, t.layout_json, t.route_json FROM templates t "
		    "WHERE t.id = $2 AND t.retired_at IS NULL RETURNING id", 2, p);
	} else if (file != NULL && file->valsz > 5 && file->valsz <= UPLOAD_MAX_BYTES &&
	    memcmp(file->val, "%PDF-", 5) == 0) {
		if (!chunked)
			total = file->valsz;
		else {
			snprintf(total_buf, sizeof(total_buf), "%zu", total);
			snprintf(received_buf, sizeof(received_buf), "%zu", file->valsz);
			p[2] = total_buf;
			p[3] = received_buf;
		}
		res = db_q(pg, "INSERT INTO documents (drafter_user, source_total, source_received) "
		    "VALUES ($1, $2::int, $3::int) RETURNING id, "
		    "json_build_object('id',id,'upload_offset',source_received,'upload_total',source_total)::text", 3,
		    (const char *[]){ id->user, p[2], p[3] });
	} else {
		db_do(pg, "ROLLBACK", 0, NULL);
		send_err(r, KHTTP_400, "upload a PDF (max 32 MiB) or pick a template");
		return;
	}
	if (res == NULL || PQntuples(res) != 1) {
		db_do(pg, "ROLLBACK", 0, NULL);
		send_err(r, KHTTP_400, "could not create document");
		if (res != NULL)
			PQclear(res);
		return;
	}
	docid = PQgetvalue(res, 0, 0);
	doc_path(dir, sizeof(dir), docid, NULL);
	doc_path(path, sizeof(path), docid, "source.pdf");
	snprintf(src, sizeof(src), "%s/templates/%s.pdf", conf_get(&cf, "data_dir",
	    "/var/lib/signet"), tpl ? tpl : "");
	if (mkdir_p(dir, 0770) == -1 ||
	    (tpl != NULL && *tpl ? copy_file(src, path) :
	    upload_chunk(dir, total, 0, 0, file->val, file->valsz, err, sizeof(err))) < 0 ||
	    log_event(pg, docid, id->user, "CREATED", "") == -1) {
		db_do(pg, "ROLLBACK", 0, NULL);
		unlink(path);
		doc_path(path, sizeof(path), docid, "source.part");
		unlink(path);
		rmdir(dir);
		send_err(r, KHTTP_500, "could not store or record the PDF");
	} else if (db_do(pg, "COMMIT", 0, NULL) == -1) {
		/* Retain files: the document's commit may have reached PostgreSQL. */
		db_do(pg, "ROLLBACK", 0, NULL);
		send_err(r, KHTTP_503, "creation commit uncertain; reload your documents");
	} else {
		if (chunked)
			send_json(r, KHTTP_201, PQgetvalue(res, 0, 1));
		else {
			snprintf(body, sizeof(body), "{\"id\":\"%s\"}", docid);
			send_json(r, KHTTP_201, body);
		}
	}
	PQclear(res);
}

static void
h_doc_upload(struct kreq *r, PGconn *pg, const struct ident *id, const char *docid)
{
	struct kpair *file = http_field(r, "file");
	const char *p[3] = { docid, id->user, NULL };
	char dir[600], err[256], next_buf[32];
	size_t offset, total, received;
	PGresult *res;
	int next, ack_col = 2;

	if (!ident_has_role(id, &cf, "drafter")) {
		send_err(r, KHTTP_403, "drafter role required");
		return;
	}
	if (upload_number(http_field_str(r, "offset"), &offset) == -1 ||
	    file == NULL || file->valsz == 0 || file->valsz > UPLOAD_CHUNK_BYTES) {
		send_err(r, KHTTP_400, "offset and a PDF chunk within 256 KiB required");
		return;
	}
	if (db_do(pg, "BEGIN", 0, NULL) == -1) {
		send_err(r, KHTTP_500, "database error");
		return;
	}
	res = db_q(pg, "SELECT source_total, source_received, "
	    "json_build_object('upload_offset',source_received,'upload_total',source_total)::text FROM documents "
	    "WHERE id=$1 AND drafter_user=$2 AND status='DRAFT' "
	    "AND source_total IS NOT NULL FOR UPDATE", 2, p);
	if (res == NULL) {
		db_do(pg, "ROLLBACK", 0, NULL);
		send_err(r, KHTTP_500, "database error");
		return;
	}
	if (PQntuples(res) != 1) {
		PQclear(res);
		db_do(pg, "ROLLBACK", 0, NULL);
		send_err(r, KHTTP_409, "only your own draft upload can accept chunks");
		return;
	}
	total = (size_t)strtoul(PQgetvalue(res, 0, 0), NULL, 10);
	received = (size_t)strtoul(PQgetvalue(res, 0, 1), NULL, 10);
	doc_path(dir, sizeof(dir), docid, NULL);
	next = upload_chunk(dir, total, received, offset, file->val, file->valsz, err, sizeof(err));
	if (next < 0) {
		PQclear(res);
		db_do(pg, "ROLLBACK", 0, NULL);
		send_err(r, next == -2 ? KHTTP_409 : KHTTP_503, err);
		return;
	}
	snprintf(next_buf, sizeof(next_buf), "%d", next);
	p[2] = next_buf;
	if (next != (int)received) {
		PQclear(res);
		res = db_q(pg, "UPDATE documents SET source_received=$3::int "
		    "WHERE id=$1 AND drafter_user=$2 RETURNING "
		    "json_build_object('upload_offset',source_received,'upload_total',source_total)::text", 3, p);
		ack_col = 0;
		if (res == NULL || PQntuples(res) != 1) {
			if (res != NULL)
				PQclear(res);
			db_do(pg, "ROLLBACK", 0, NULL);
			send_err(r, KHTTP_500, "could not record chunk; retry the same offset");
			return;
		}
	}
	if (db_do(pg, "COMMIT", 0, NULL) == -1) {
		PQclear(res);
		db_do(pg, "ROLLBACK", 0, NULL);
		send_err(r, KHTTP_503, "chunk commit uncertain; retry the same offset");
		return;
	}
	send_json(r, KHTTP_200, PQgetvalue(res, 0, ack_col));
	PQclear(res);
}

#define RETRY_ACTOR "($3::boolean OR " \
	"(d.render_kind = 'stamp' AND d.drafter_user = $2) OR " \
	"(d.render_kind = 'sign' AND (" \
	"d.route_json->'parties'->(d.current_party - 1)->>'signer' = $2 OR " \
	"d.route_json->'parties'->(d.current_party - 2)->>'signer' = $2)) OR " \
	"(d.render_kind = 'release' AND " \
	"d.route_json->'parties'->(d.current_party - 1)->>'signer' = $2))"

static void
h_doc_get(struct kreq *r, PGconn *pg, const struct ident *id, const char *docid)
{
	const char *p[] = { docid, id->user,
	    ident_has_role(id, &cf, "admin") ? "t" : "f",
	    ident_has_role(id, &cf, "signer") ? "t" : "f",
	    *conf_get(&cf, "timestamp.url", "") && *conf_get(&cf, "timestamp.ca_file", "") ? "t" : "f" };

	send_sql_json(r, pg,
	    "SELECT row_to_json(t)::text FROM (SELECT d.id, d.status, d.title, "
	    "d.drafter_user, d.series_code, d.serial, d.doc_date, d.org_code, "
	    "d.layout_json AS layout, d.route_json AS route, d.revision, "
	    "d.current_party, d.render_seq, d.rendered_seq, d.render_kind, "
	    "d.source_total AS upload_total, d.source_received AS upload_offset, "
	    "coalesce(d.source_received<d.source_total,false) AS uploading, "
	    "(d.rendered_seq < d.render_seq) AS rendering, "
	    "(d.status = 'PENDING' AND d.rendered_seq < d.render_seq AND "
	    RETRY_ACTOR ") AS can_retry, d.render_error, d.final_sha256, "
	    "d.created_at, d.submitted_at, d.released_at, "
	    "(SELECT max(decided_at) FROM doc_decisions WHERE doc_id=d.id AND revision=d.revision "
	    "AND decision='SIGNOFF') AS signed_at, "
	    "(SELECT timestamped_at FROM document_timestamps WHERE doc_id=d.id AND state='timestamped' "
	    "AND revision=d.revision AND pdf_sha256=d.final_sha256) AS timestamped_at, "
	    "coalesce((SELECT CASE WHEN state='pending' AND deadline<=clock_timestamp() "
	    "THEN 'unavailable' ELSE state END FROM document_timestamps WHERE doc_id=d.id "
	    "AND revision=d.revision AND pdf_sha256=d.final_sha256), "
	    "CASE WHEN d.status='RELEASED' AND $5::boolean THEN CASE "
	    "WHEN d.released_at>clock_timestamp()-interval '1 hour' THEN 'pending' ELSE 'unavailable' END "
	    "ELSE 'not_requested' END) AS timestamp_status, "
	    "coalesce((SELECT attempts FROM document_timestamps WHERE doc_id=d.id),0) AS timestamp_attempts, "
	    "(SELECT s.pattern FROM series s WHERE s.code = d.series_code) AS series_pattern, "
	    "(d.drafter_user = $2 AND d.status IN ('DRAFT','CORRECTION_REQUIRED') "
	    "AND coalesce(d.source_received=d.source_total,true)) AS can_edit, "
	    "($4::boolean AND " CAN_DECIDE("$2") ") AS can_decide, "
	    "($3::boolean OR " ROUTE_ACCESS("$2") ") AS can_see_stamped, "
	    "(SELECT coalesce(json_agg(e ORDER BY e.id), '[]') FROM ("
	    "SELECT id, actor, action, detail, at FROM doc_events WHERE doc_id = d.id) e) AS events, "
	    "(SELECT coalesce(json_agg(x ORDER BY x.decided_at), '[]') FROM ("
	    "SELECT revision, party, signer, decision, comment, decided_at, facsimile_id "
	    "FROM doc_decisions WHERE doc_id = d.id) x) AS decisions "
	    "FROM documents d WHERE d.id = $1 AND (d.drafter_user = $2 OR $3::boolean "
	    "OR " ROUTE_ACCESS("$2") ")) t", 5, p);
}

static void
h_doc_save(struct kreq *r, PGconn *pg, const struct ident *id, const char *docid)
{
	const char *json = http_field_str(r, "json"), *msg, *p[7];
	yyjson_doc *doc;
	yyjson_val *root, *layout, *route;
	char *ltxt = NULL, *rtxt = NULL;
	PGresult *res;

	if (json == NULL || strlen(json) > MAX_JSON_BYTES ||
	    (doc = yyjson_read(json, strlen(json), 0)) == NULL) {
		send_err(r, KHTTP_400, "json field missing, malformed or over 1 MiB");
		return;
	}
	root = yyjson_doc_get_root(doc);
	layout = yyjson_obj_get(root, "layout");
	route = yyjson_obj_get(root, "route");
	if ((msg = check_layout(layout)) != NULL || (msg = check_route(route)) != NULL ||
	    (msg = check_zones(layout, route)) != NULL) {
		send_err(r, KHTTP_400, msg);
		goto out;
	}
	ltxt = yyjson_val_write(layout, 0, NULL);
	rtxt = yyjson_val_write(route, 0, NULL);
	p[0] = docid;
	p[1] = id->user;
	p[2] = yyjson_get_str(yyjson_obj_get(root, "title"));
	p[3] = yyjson_get_str(yyjson_obj_get(root, "series_code"));
	p[4] = yyjson_get_str(yyjson_obj_get(root, "org_code"));
	p[5] = ltxt;
	p[6] = rtxt;
	if (p[2] == NULL)
		p[2] = "";
	if (p[3] != NULL && *p[3] == '\0')
		p[3] = NULL;
	if (p[4] != NULL && *p[4] == '\0')
		p[4] = NULL;
	if (ltxt == NULL || rtxt == NULL || strlen(p[2]) > 200 ||
	    (p[3] != NULL && !is_safe_name(p[3])) ||
	    (p[4] != NULL && !is_safe_name(p[4]))) {
		send_err(r, KHTTP_400, "bad title, series, or org");
		goto out;
	}
	/* the series is frozen once a serial number has been allocated */
	res = db_q(pg, "UPDATE documents SET title = $3, "
	    "series_code = CASE WHEN serial IS NULL THEN $4 ELSE series_code END, "
	    "org_code = $5, layout_json = $6::jsonb, route_json = $7::jsonb WHERE id = $1 "
	    "AND drafter_user = $2 AND status IN ('DRAFT','CORRECTION_REQUIRED') "
	    "AND coalesce(source_received=source_total,true)", 7, p);
	if (res == NULL)
		send_err(r, KHTTP_400, "save failed (unknown series?)");
	else if (strcmp(PQcmdTuples(res), "1") != 0)
		send_err(r, KHTTP_409, "document is not editable by you");
	else
		send_json(r, KHTTP_200, "{\"ok\":true}");
	if (res != NULL)
		PQclear(res);
out:
	free(ltxt);
	free(rtxt);
	yyjson_doc_free(doc);
}

static void
h_doc_submit(struct kreq *r, PGconn *pg, const struct ident *id, const char *docid)
{
	const char *p[5] = { docid, id->user, NULL, NULL, NULL };
	PGresult *res = NULL, *r2 = NULL;
	yyjson_doc *ldoc = NULL, *rdoc = NULL;
	char err[512] = "", serial[256], body[64], *rev = NULL;
	char key[37], name[64], frozen_dir[1024] = "", *frozen = NULL;
	int has_serial, has_series, commit_attempted = 0;
	const char *submit_action;

	if (db_do(pg, "BEGIN", 0, NULL) == -1) {
		send_err(r, KHTTP_500, "database error");
		return;
	}
	/* Match MAX_JSON_BYTES before transferring legacy JSON into this process. */
	res = db_q(pg, "SELECT CASE WHEN octet_length(layout_json::text) <= 1024 * 1024 "
	    "THEN layout_json::text END, "
	    "CASE WHEN octet_length(route_json::text) <= 1024 * 1024 "
	    "THEN route_json::text END, series_code, "
	    "serial, org_code, status::text, title, revision + 1 FROM documents WHERE id = $1 AND drafter_user = $2 "
	    "AND status IN ('DRAFT','CORRECTION_REQUIRED') "
	    "AND coalesce(source_received=source_total,true) FOR UPDATE", 2, p);
	if (res == NULL || PQntuples(res) != 1) {
		snprintf(err, sizeof(err), "document is not submittable by you");
		goto fail;
	}
	if (PQgetisnull(res, 0, 0) || PQgetisnull(res, 0, 1)) {
		snprintf(err, sizeof(err), "layout and route must each fit within 1 MiB");
		goto fail;
	}
	submit_action = strcmp(PQgetvalue(res, 0, 5), "CORRECTION_REQUIRED") == 0
	    ? "RESUBMITTED" : "SUBMITTED";
	if (strspn(PQgetvalue(res, 0, 6), " \t\r\n") == strlen(PQgetvalue(res, 0, 6))) {
		snprintf(err, sizeof(err), "document title is required");
		goto fail;
	}
	const char *org_code = PQgetisnull(res, 0, 4) ? NULL : PQgetvalue(res, 0, 4);
	if (org_code == NULL || !*org_code) {
		snprintf(err, sizeof(err), "document must have an organisation selected");
		goto fail;
	}
	has_series = !PQgetisnull(res, 0, 2);
	has_serial = !PQgetisnull(res, 0, 3);
	ldoc = yyjson_read(PQgetvalue(res, 0, 0), strlen(PQgetvalue(res, 0, 0)), 0);
	rdoc = yyjson_read(PQgetvalue(res, 0, 1), strlen(PQgetvalue(res, 0, 1)), 0);
	if (ldoc == NULL || rdoc == NULL ||
	    check_submittable(yyjson_doc_get_root(ldoc), yyjson_doc_get_root(rdoc),
	    org_code, has_series, err, sizeof(err)) == -1)
		goto fail;

	r2 = db_q(pg, "SELECT gen_random_uuid()::text", 0, NULL);
	if (r2 == NULL || PQntuples(r2) != 1) {
		snprintf(err, sizeof(err), "could not allocate revision snapshot");
		goto fail;
	}
	snprintf(key, sizeof(key), "%s", PQgetvalue(r2, 0, 0));
	PQclear(r2);
	r2 = NULL;
	snprintf(name, sizeof(name), "snapshot-%s", key);
	doc_path(frozen_dir, sizeof(frozen_dir), docid, name);
	frozen = snapshot_create(&cf, redis_get(&cf), org_code,
	    atoi(PQgetvalue(res, 0, 7)), yyjson_doc_get_root(ldoc), frozen_dir, err, sizeof(err));
	if (frozen == NULL) {
		frozen_dir[0] = '\0'; /* snapshot_create cleans only a directory it created. */
		goto fail;
	}
	p[3] = frozen;
	p[4] = key;

	if (has_series) {
		const char *sp[] = { PQgetvalue(res, 0, 2) };
		PGresult *sres = db_q(pg, "SELECT retired_at FROM series WHERE code = $1", 1, sp);
		if (sres == NULL || PQntuples(sres) != 1) {
			if (sres != NULL)
				PQclear(sres);
			snprintf(err, sizeof(err), "could not read series");
			goto fail;
		}
		if (sres != NULL) {
			if (!PQgetisnull(sres, 0, 0)) {
				snprintf(err, sizeof(err), "this series has been retired");
				PQclear(sres);
				goto fail;
			}
			PQclear(sres);
		}
	}
	if (has_series && !has_serial) {
		const char *sp[] = { PQgetvalue(res, 0, 2) };

		/* rolled back with the transaction if anything below fails */
		r2 = db_q(pg, "WITH c AS (INSERT INTO series_counters (series_code, "
		    "day, seq) VALUES ($1, CURRENT_DATE, 1) ON CONFLICT (series_code, "
		    "day) DO UPDATE SET seq = series_counters.seq + 1 RETURNING seq) "
		    "SELECT c.seq, s.pattern, CURRENT_DATE::text FROM c, series s "
		    "WHERE s.code = $1", 1, sp);
		if (r2 == NULL || PQntuples(r2) != 1 ||
		    series_expand(PQgetvalue(r2, 0, 1), PQgetvalue(r2, 0, 2),
		    atoi(PQgetvalue(r2, 0, 0)), serial, sizeof(serial)) == -1) {
			snprintf(err, sizeof(err), "could not allocate a serial number");
			goto fail;
		}
		p[2] = serial;
	}
	if (r2 != NULL)
		PQclear(r2);
	r2 = db_q(pg, "UPDATE documents SET status = 'PENDING'::doc_status, "
	    "revision = revision + 1, render_seq = render_seq + 1, "
	    "render_kind = 'stamp', current_party = 1, "
	    "snapshot_json = $4::jsonb, snapshot_id = $5::uuid, "
	    "serial = COALESCE(serial, $3), "
	    "doc_date = COALESCE(doc_date, CURRENT_DATE), "
	    "submitted_at = CURRENT_TIMESTAMP, render_error = NULL "
	    "WHERE id = $1 AND drafter_user = $2 "
	    "RETURNING revision::text, render_seq::text", 5, p);
	if (r2 == NULL || PQntuples(r2) != 1 || (rev = strdup(PQgetvalue(r2, 0, 0))) == NULL ||
	    log_event(pg, docid, id->user, submit_action, rev) == -1) {
		snprintf(err, sizeof(err), "submit failed");
		goto fail;
	}
	/* An ambiguous COMMIT must never delete potentially committed inputs. */
	commit_attempted = 1;
	if (db_do(pg, "COMMIT", 0, NULL) == -1) {
		snprintf(err, sizeof(err), "submit commit outcome unknown; reload document before retrying");
		goto fail;
	}
	if (enqueue(docid, rev, PQgetvalue(r2, 0, 1), "stamp") == -1)
		send_err(r, KHTTP_503, "submitted, but the stamping queue is down; "
		    "use 'Retry stamping' once it is back");
	else {
		snprintf(body, sizeof(body), "{\"ok\":true,\"revision\":%d}", atoi(rev));
		send_json(r, KHTTP_200, body);
	}
	goto done;
fail:
	db_do(pg, "ROLLBACK", 0, NULL);
	if (!commit_attempted)
		snapshot_remove(frozen_dir);
	send_err(r, KHTTP_409, err);
done:
	free(frozen);
	free(rev);
	if (res != NULL)
		PQclear(res);
	if (r2 != NULL)
		PQclear(r2);
	yyjson_doc_free(ldoc);
	yyjson_doc_free(rdoc);
}

static void
h_doc_rerender(struct kreq *r, PGconn *pg, const struct ident *id, const char *docid)
{
	const char *p[] = { docid, id->user,
	    ident_has_role(id, &cf, "admin") ? "t" : "f" };
	PGresult *res;

	res = db_q(pg, "SELECT " RETRY_ACTOR " FROM documents d WHERE id = $1", 3, p);
	if (res == NULL) {
		send_err(r, KHTTP_500, "database error");
		return;
	}
	if (PQntuples(res) != 1 || PQgetvalue(res, 0, 0)[0] != 't') {
		PQclear(res);
		send_err(r, KHTTP_403, "not permitted to retry this render");
		return;
	}
	PQclear(res);
	res = db_q(pg, "WITH work AS (UPDATE documents d SET render_error = NULL, "
	    "render_seq = render_seq + 1 WHERE id = $1 AND " RETRY_ACTOR
	    " AND status IN " PENDING " AND rendered_seq < render_seq "
	    "AND render_kind IN ('stamp','sign','release') "
	    "RETURNING id, revision, render_seq, render_kind), event AS ("
	    "INSERT INTO doc_events(doc_id,actor,action,detail) "
	    "SELECT id, $2::varchar, 'RETRY', render_kind FROM work) "
	    "SELECT revision::text, render_seq::text, render_kind FROM work", 3, p);
	if (res == NULL)
		send_err(r, KHTTP_500, "database error");
	else if (PQntuples(res) != 1)
		send_err(r, KHTTP_409, "nothing to re-render");
	else {
		if (enqueue(docid, PQgetvalue(res, 0, 0), PQgetvalue(res, 0, 1),
		    PQgetvalue(res, 0, 2)) == -1)
			send_err(r, KHTTP_503, "render queue is down; retry rendering once it is back");
		else
			send_json(r, KHTTP_200, "{\"ok\":true}");
	}
	if (res != NULL)
		PQclear(res);
}

static double
json_number(yyjson_val *obj, const char *key, double fallback)
{
	yyjson_val *v = yyjson_obj_get(obj, key);

	return yyjson_is_num(v) ? yyjson_get_num(v) : fallback;
}

static const char *
check_placement(yyjson_val *layout, yyjson_val *zone, yyjson_val *pl,
    double aspect, double page_w, double page_h)
{
	yyjson_val *coords = yyjson_obj_get(pl, "coords");
	yyjson_val *zc = yyjson_obj_get(zone, "coords");
	yyjson_val *page = yyjson_obj_get(pl, "page");
	double c[4], zw, zh, rw, rh, w, h, fit_w, fit_h;
	int i;

	if (!yyjson_is_obj(pl) || !yyjson_is_int(page) ||
	    yyjson_get_sint(page) != yyjson_get_sint(yyjson_obj_get(zone, "page")) ||
	    !yyjson_is_arr(coords) || yyjson_arr_size(coords) != 4)
		return "placement needs the zone page and four numeric coordinates";
	zw = json_number(zone, "ref_w", json_number(layout, "reference_width", 0));
	zh = json_number(zone, "ref_h", json_number(layout, "reference_height", 0));
	rw = json_number(pl, "ref_w", 0);
	rh = json_number(pl, "ref_h", 0);
	if (!isfinite(rw) || !isfinite(rh) || rw <= 0 || rh <= 0 || zw <= 0 || zh <= 0)
		return "placement needs positive reference dimensions";
	for (i = 0; i < 4; i++) {
		if (!yyjson_is_num(yyjson_arr_get(coords, i)))
			return "placement coordinates must be finite numbers";
		c[i] = yyjson_get_num(yyjson_arr_get(coords, i)) * (i % 2 ? zh / rh : zw / rw);
		if (!isfinite(c[i]))
			return "placement coordinates must be finite numbers";
	}
	w = c[2] - c[0];
	h = c[3] - c[1];
	if (w <= 0 || h <= 0 || c[0] < yyjson_get_num(yyjson_arr_get(zc, 0)) ||
	    c[1] < yyjson_get_num(yyjson_arr_get(zc, 1)) ||
	    c[2] > yyjson_get_num(yyjson_arr_get(zc, 2)) ||
	    c[3] > yyjson_get_num(yyjson_arr_get(zc, 3)))
		return "placement outside zone bounds or not a positive rectangle";
	fit_w = fmin(w / zw * page_w, h / zh * page_h * aspect);
	fit_h = fit_w / aspect;
	if (fit_w + 1e-7 < json_number(zone, "min_w", 0) / zw * page_w ||
	    fit_h + 1e-7 < json_number(zone, "min_h", 0) / zh * page_h)
		return "placement too small for the zone minimum dimensions";
	return NULL;
}

static void
h_doc_decide(struct kreq *r, PGconn *pg, const struct ident *id, const char *docid)
{
	const char *decision = http_field_str(r, "decision");
	const char *comment = http_field_str(r, "comment");
	const char *placement_json = http_field_str(r, "placement");
	const char *chosen = http_field_str(r, "facsimile_id");
	char facsimile[37] = "";
	const char *p[5], *code, *action;
	char err[512] = "", detail[4608];
	PGresult *res = NULL, *job_res = NULL;
	int party, parties, is_last_party, has_zone;
	yyjson_val *layout, *imprints, *imp;
	yyjson_doc *layout_doc = NULL, *placement_doc = NULL;
	char party_name[50] = "";
	size_t i, max;
	const char *type, *pname;

	if ((chosen != NULL && !is_uuid(chosen)) ||
	    (http_field(r, "facsimile_id") != NULL && chosen == NULL)) {
		send_err(r, KHTTP_400, "invalid facsimile reference");
		return;
	}
	if (http_field(r, "placement") != NULL &&
	    (placement_json == NULL || strlen(placement_json) > MAX_JSON_BYTES)) {
		send_err(r, KHTTP_400, "placement must be valid text within 1 MiB");
		return;
	}
	if (comment == NULL)
		comment = "";
	if (strlen(comment) > 4096) {
		send_err(r, KHTTP_400, "comment must be at most 4096 bytes");
		return;
	}
	if (decision != NULL && (strcmp(decision, "signoff") == 0 || strcmp(decision, "approve") == 0))
		code = "SIGNOFF";
	else if (decision != NULL && strcmp(decision, "correction") == 0)
		code = "CORRECTION";
	else if (decision != NULL && strcmp(decision, "disapprove") == 0)
		code = "DISAPPROVE";
	else {
		send_err(r, KHTTP_400, "decision must be signoff, correction or disapprove");
		return;
	}
	if (code[0] != 'S' && *comment == '\0') {
		send_err(r, KHTTP_400, "a comment is required when not approving");
		return;
	}
	if (!ident_has_role(id, &cf, "signer")) {
		send_err(r, KHTTP_403, "signer role required");
		return;
	}
	if (db_do(pg, "BEGIN", 0, NULL) == -1) {
		send_err(r, KHTTP_500, "database error");
		return;
	}
	p[0] = docid;
	p[1] = id->user;
	res = db_q(pg, "SELECT d.current_party, jsonb_array_length(d.route_json->'parties'), "
	    "d.route_json->'parties'->(d.current_party - 1)->>'name', "
	    "d.revision::text, d.render_seq::text, "
	    "CASE WHEN octet_length(d.layout_json::text) <= 1024 * 1024 THEN d.layout_json::text END "
	    "FROM documents d WHERE d.id = $1 AND "
	    CAN_DECIDE("$2") " FOR UPDATE", 2, p);
	if (res == NULL || PQntuples(res) != 1) {
		snprintf(err, sizeof(err), "this document is not waiting for your decision");
		goto fail;
	}
	party = atoi(PQgetvalue(res, 0, 0));
	parties = atoi(PQgetvalue(res, 0, 1));
	strncpy(party_name, PQgetvalue(res, 0, 2), sizeof(party_name)-1);
	p[2] = PQgetvalue(res, 0, 3);
	p[3] = PQgetvalue(res, 0, 4);
	is_last_party = (party >= parties);

	has_zone = 0;
	if (code[0] == 'S') {
		const char *layout_str = PQgetvalue(res, 0, 5), *msg;
		yyjson_val *zone = NULL;

		if (PQgetisnull(res, 0, 5)) {
			snprintf(err, sizeof(err), "stored layout must fit within 1 MiB; request a correction");
			goto fail;
		}
		layout_doc = yyjson_read(layout_str, strlen(layout_str), 0);
		if (layout_doc == NULL) {
			snprintf(err, sizeof(err), "invalid stored layout");
			goto fail;
		}
		layout = yyjson_doc_get_root(layout_doc);
		imprints = yyjson_obj_get(layout, "imprints");
		yyjson_arr_foreach(imprints, i, max, imp) {
			type = yyjson_get_str(yyjson_obj_get(imp, "type"));
			pname = yyjson_get_str(yyjson_obj_get(imp, "party"));
			if (type != NULL && strcmp(type, "signature_zone") == 0 &&
			    pname != NULL && strcmp(pname, party_name) == 0)
				zone = imp;
		}
		has_zone = zone != NULL;
		if (has_zone) {
			PGresult *fres;
			char source[700];
			double aspect, page_w, page_h;
			int enrolled;

			if (chosen == NULL && db_do(pg, "SELECT pg_advisory_xact_lock(hashtextextended($1,0))",
			    1, (const char *[]){ id->user }) == -1)
				goto fail;
			fres = db_q(pg, "SELECT width, height, id::text FROM facsimiles WHERE username = $1 "
			    "AND (($2::uuid IS NULL AND is_default) OR id=$2::uuid) "
			    "AND enrolled_at IS NOT NULL AND width > 0 AND height > 0 FOR SHARE",
			    2, (const char *[]){ id->user, chosen });
			enrolled = fres != NULL && PQntuples(fres) == 1;
			aspect = enrolled ? atof(PQgetvalue(fres, 0, 0)) / atof(PQgetvalue(fres, 0, 1)) : 0;

			if (enrolled)
				snprintf(facsimile, sizeof(facsimile), "%s", PQgetvalue(fres, 0, 2));
			if (fres != NULL)
				PQclear(fres);
			if (!enrolled) {
				snprintf(err, sizeof(err), "enrol your signature first");
				goto fail;
			}
			doc_path(source, sizeof(source), docid, "source.pdf");
			if (render_page_size(source, yyjson_get_int(yyjson_obj_get(zone, "page")), &page_w, &page_h) == -1) {
				snprintf(err, sizeof(err), "signature zone page does not exist");
				goto fail;
			}
			placement_doc = placement_json == NULL ? NULL :
			    yyjson_read(placement_json, strlen(placement_json), 0);
			msg = placement_doc == NULL ? "placement required for signature zones" :
			    check_placement(layout, zone, yyjson_doc_get_root(placement_doc), aspect, page_w, page_h);
			if (msg != NULL) {
				snprintf(err, sizeof(err), "%s", msg);
				goto fail;
			}
		}
	}
	if (!has_zone && (placement_json != NULL || chosen != NULL)) {
		snprintf(err, sizeof(err), "placement and facsimile are only allowed for a zone sign-off");
		goto fail;
	}

	/* Record the decision */
	{
		char party_str[12];
		snprintf(party_str, sizeof(party_str), "%d", party);

		if (placement_json != NULL) {
			const char *ip[] = { docid, p[2], party_str, id->user, code, comment, placement_json, facsimile };
			if (db_do(pg, "INSERT INTO doc_decisions (doc_id, revision, party, "
			    "signer, decision, comment, placement, facsimile_id) VALUES ($1, $2::int, $3::int, $4, $5, $6, $7::jsonb, $8::uuid)",
			    8, ip) == -1) {
				snprintf(err, sizeof(err), "could not record the decision");
				goto fail;
			}
		} else {
			const char *ip[] = { docid, p[2], party_str, id->user, code, comment };
			if (db_do(pg, "INSERT INTO doc_decisions (doc_id, revision, party, "
			    "signer, decision, comment) VALUES ($1, $2::int, $3::int, $4, $5, $6)",
			    6, ip) == -1) {
				snprintf(err, sizeof(err), "could not record the decision");
				goto fail;
			}
		}
	}

	action = NULL;
	if (code[0] == 'S') {
		if (!is_last_party && db_do(pg, "UPDATE documents SET "
		    "current_party = current_party + 1 WHERE id = $1", 1, p) == -1)
			goto fail;
		if (has_zone || is_last_party) {
			const char *jp[] = { docid, is_last_party ? "release" : "sign" };

			job_res = db_q(pg, "UPDATE documents SET render_seq = render_seq + 1, "
			    "render_kind = $2, render_error = NULL WHERE id = $1 "
			    "RETURNING revision::text, render_seq::text, render_kind", 2, jp);
			if (job_res == NULL || PQntuples(job_res) != 1)
				goto fail;
		}
		action = "SIGNOFF";
	} else {
		if (db_do(pg, code[0] == 'C'
		    ? "UPDATE documents SET status = 'CORRECTION_REQUIRED' WHERE id = $1"
		    : "UPDATE documents SET status = 'DISAPPROVED' WHERE id = $1", 1, p) == -1)
			goto fail;
		action = code[0] == 'C' ? "CORRECTION_REQUIRED" : "DISAPPROVED";
	}

	snprintf(detail, sizeof(detail), "revision %s, party %d (%s)%s%s: %s",
	    p[2], party, party_name, *facsimile ? ", facsimile " : "", facsimile, comment);
	if (log_event(pg, docid, id->user, action, detail) == -1 ||
	    db_do(pg, "COMMIT", 0, NULL) == -1)
		goto fail;
	if (code[0] != 'S') {
		char path[700];

		doc_path(path, sizeof(path), docid, "stamped.pdf");
		unlink(path);
		snprintf(path, sizeof(path), "%s/docs/%s/render-%s.pdf",
		    conf_get(&cf, "data_dir", "/var/lib/signet"), docid, p[3]);
		unlink(path);
	}
	/* Publish only committed work; a queue outage can be retried by the signer. */
	if (job_res != NULL && enqueue(docid, PQgetvalue(job_res, 0, 0),
	    PQgetvalue(job_res, 0, 1), PQgetvalue(job_res, 0, 2)) == -1)
		send_err(r, KHTTP_503, "decision recorded, but the render queue is down; retry rendering");
	else
		send_json(r, KHTTP_200, "{\"ok\":true}");
	goto done;
fail:
	db_do(pg, "ROLLBACK", 0, NULL);
	send_err(r, KHTTP_409, *err ? err : "decision failed");
done:
	if (res != NULL)
		PQclear(res);
	if (layout_doc != NULL)
		yyjson_doc_free(layout_doc);
	if (job_res != NULL)
		PQclear(job_res);
	yyjson_doc_free(placement_doc);
}

static void
h_doc_delete(struct kreq *r, PGconn *pg, const struct ident *id, const char *docid)
{
	const char *p[] = { docid, id->user };
	char path[700];
	PGresult *res;

	res = db_q(pg, "DELETE FROM documents WHERE id = $1 AND drafter_user = $2 "
	    "AND status = 'DRAFT' AND serial IS NULL", 2, p);
	if (res == NULL || strcmp(PQcmdTuples(res), "1") != 0)
		send_err(r, KHTTP_409, "only your own unsubmitted drafts can be deleted");
	else {
		doc_path(path, sizeof(path), docid, "source.pdf");
		unlink(path);
		doc_path(path, sizeof(path), docid, "source.part");
		unlink(path);
		doc_path(path, sizeof(path), docid, NULL);
		rmdir(path);
		send_json(r, KHTTP_200, "{\"ok\":true}");
	}
	if (res != NULL)
		PQclear(res);
}

static void
h_doc_file(struct kreq *r, PGconn *pg, const struct ident *id, const char *docid,
    const char *kind)
{
	const char *p[] = { docid, id->user,
	    ident_has_role(id, &cf, "admin") ? "t" : "f" };
	char path[700], name[64];
	PGresult *res;
	int is_drafter, in_route, admin = p[2][0] == 't';
	unsigned char *token;
	size_t token_size;
	const char *status;

	res = db_q(pg, "SELECT d.drafter_user = $2, " ROUTE_ACCESS("$2") ", d.status::text "
	    "FROM documents d WHERE d.id = $1 AND (d.drafter_user = $2 "
	    "OR $3::boolean OR " ROUTE_ACCESS("$2") ") "
	    "AND coalesce(d.source_received=d.source_total,true)", 3, p);
	if (res == NULL || PQntuples(res) != 1) {
		send_err(r, KHTTP_404, "not found");
		goto out;
	}
	is_drafter = PQgetvalue(res, 0, 0)[0] == 't';
	in_route = PQgetvalue(res, 0, 1)[0] == 't';
	status = PQgetvalue(res, 0, 2);
	if (strcmp(status, "DRAFT") == 0)
		in_route = 0;
	if (strcmp(kind, "source") != 0 && strcmp(kind, "proof") != 0 &&
	    strcmp(kind, "stamped") != 0 && strcmp(kind, "final") != 0 &&
	    strcmp(kind, "timestamp") != 0) {
		send_err(r, KHTTP_404, "not found");
		goto out;
	}
	if (((strcmp(kind, "final") == 0 || strcmp(kind, "timestamp") == 0) &&
	    strcmp(status, "RELEASED") != 0) ||
	    (strcmp(kind, "stamped") == 0 && strcmp(status, "PENDING") != 0)) {
		send_err(r, KHTTP_404, "file not available");
		goto out;
	}
	/* Only a party whose turn has arrived (or an admin) sees facsimiles. */
	if (!(admin || in_route || (is_drafter && strcmp(kind, "stamped") != 0))) {
		send_err(r, KHTTP_403, "forbidden");
		goto out;
	}
	if (strcmp(kind, "timestamp") == 0) {
		PQclear(res);
		res = db_q(pg, "SELECT t.response FROM document_timestamps t JOIN documents d ON d.id=t.doc_id "
		    "AND d.revision=t.revision AND d.final_sha256=t.pdf_sha256 "
		    "WHERE t.doc_id=$1 AND t.state='timestamped' AND d.status='RELEASED'", 1, p);
		if (res == NULL) {
			send_err(r, KHTTP_503, "timestamp unavailable");
			goto out;
		}
		if (PQntuples(res) != 1) {
			send_err(r, KHTTP_404, "timestamp not available");
			goto out;
		}
		if (PQgetisnull(res, 0, 0)) {
			send_err(r, KHTTP_503, "timestamp unavailable");
			goto out;
		}
		token = PQunescapeBytea((const unsigned char *)PQgetvalue(res, 0, 0), &token_size);
		if (token == NULL || token_size == 0 || token_size > 65536) {
			PQfreemem(token);
			send_err(r, KHTTP_503, "timestamp unavailable");
			goto out;
		}
		khttp_head(r, kresps[KRESP_STATUS], "%s", khttps[KHTTP_200]);
		khttp_head(r, kresps[KRESP_CONTENT_TYPE], "application/timestamp-reply");
		khttp_head(r, kresps[KRESP_CACHE_CONTROL], "no-store");
		khttp_head(r, kresps[KRESP_CONTENT_DISPOSITION], "attachment; filename=timestamp.tsr");
		khttp_body(r);
		khttp_write(r, (const char *)token, token_size);
		PQfreemem(token);
		goto out;
	}
	snprintf(name, sizeof(name), "%s.pdf", kind);
	doc_path(path, sizeof(path), docid, name);
	send_file(r, path, "application/pdf", name);
out:
	if (res != NULL)
		PQclear(res);
}

static void
h_templates(struct kreq *r, PGconn *pg, const struct ident *id)
{
	const char *docid, *name, *p[3];
	char src[700], dst[700], body[128];
	PGresult *res;

	if (r->method == KMETHOD_GET) {
		const char *admin = ident_has_role(id, &cf, "admin") ? "t" : "f";
		const char *p[] = { admin };
		send_sql_json(r, pg, "SELECT coalesce(json_agg(t), '[]')::text FROM ("
		    "SELECT t.id, t.name, t.series_code, t.created_by, t.created_at, t.retired_at, "
		    "(SELECT COUNT(*) FROM documents WHERE template_id = t.id) AS linked "
		    "FROM templates t WHERE $1::boolean OR t.retired_at IS NULL "
		    "ORDER BY t.name) t", 1, p);
		return;
	}
	docid = http_field_str(r, "doc_id");
	name = http_field_str(r, "name");
	if (!ident_has_role(id, &cf, "drafter") || !is_uuid(docid) || name == NULL ||
	    *name == '\0' || strlen(name) > 200) {
		send_err(r, KHTTP_400, "drafter role, doc_id and name required");
		return;
	}
	p[0] = docid;
	p[1] = id->user;
	p[2] = name;
	res = db_q(pg, "INSERT INTO templates (name, series_code, layout_json, "
	    "route_json, created_by) SELECT $3::varchar, series_code, layout_json, route_json, "
	    "$2::varchar FROM documents WHERE id = $1 AND drafter_user = $2::varchar "
	    "AND coalesce(source_received=source_total,true) RETURNING id", 3, p);
	if (res == NULL || PQntuples(res) != 1) {
		send_err(r, KHTTP_404, "document not found");
		if (res != NULL)
			PQclear(res);
		return;
	}
	snprintf(dst, sizeof(dst), "%s/templates", conf_get(&cf, "data_dir",
	    "/var/lib/signet"));
	mkdir_p(dst, 0770);
	snprintf(dst, sizeof(dst), "%s/templates/%s.pdf", conf_get(&cf, "data_dir",
	    "/var/lib/signet"), PQgetvalue(res, 0, 0));
	doc_path(src, sizeof(src), docid, "source.pdf");
	if (copy_file(src, dst) == -1) {
		p[0] = PQgetvalue(res, 0, 0);
		db_do(pg, "DELETE FROM templates WHERE id = $1", 1, p);
		send_err(r, KHTTP_500, "could not store the template PDF");
	} else {
		snprintf(body, sizeof(body), "{\"id\":\"%s\"}", PQgetvalue(res, 0, 0));
		send_json(r, KHTTP_201, body);
	}
	PQclear(res);
}

static void
h_series(struct kreq *r, PGconn *pg, const struct ident *id)
{
	const char *p[3];
	char test[256];

	if (r->method == KMETHOD_GET) {
		const char *admin = ident_has_role(id, &cf, "admin") ? "t" : "f";
		const char *p[] = { admin };
		send_sql_json(r, pg, "SELECT coalesce(json_agg(t), '[]')::text FROM ("
		    "SELECT code, pattern, retired_at FROM series WHERE $1::boolean OR retired_at IS NULL "
		    "ORDER BY code) t", 1, p);
		return;
	}
	p[0] = http_field_str(r, "code");
	p[1] = http_field_str(r, "pattern");
	p[2] = id->user;
	if (!ident_has_role(id, &cf, "admin")) {
		send_err(r, KHTTP_403, "admin role required");
	} else if (!is_safe_name(p[0]) || p[1] == NULL || strlen(p[1]) > 150 ||
	    strstr(p[1], "{seq") == NULL ||
	    series_expand(p[1], "2026-01-31", 1, test, sizeof(test)) == -1) {
		send_err(r, KHTTP_400, "need a code and a pattern such as "
		    "SKGA/SCNREPLY/{date:%Y%m%d}/{seq:02}");
	} else if (db_do(pg, "INSERT INTO series (code, pattern, created_by) "
	    "VALUES ($1, $2, $3) ON CONFLICT (code) DO UPDATE SET pattern = $2",
	    3, p) == -1) {
		send_err(r, KHTTP_500, "database error");
	} else
		send_json(r, KHTTP_200, "{\"ok\":true}");
}

static yyjson_mut_val *
pim_org(yyjson_mut_doc *doc, yyjson_mut_val *root, const char *key, size_t len)
{
	char org[65];
	yyjson_mut_val *ent;

	if (len == 0 || len >= sizeof(org))
		return NULL;
	memcpy(org, key, len);
	org[len] = '\0';
	if (!is_safe_name(org))
		return NULL;
	ent = yyjson_mut_obj_get(root, org);
	if (ent == NULL) {
		ent = yyjson_mut_obj(doc);
		yyjson_mut_obj_add(root, yyjson_mut_strcpy(doc, org), ent);
		yyjson_mut_obj_add(ent, yyjson_mut_str(doc, "text"), yyjson_mut_obj(doc));
		yyjson_mut_obj_add(ent, yyjson_mut_str(doc, "images"), yyjson_mut_obj(doc));
	}
	return ent;
}

static void
h_pim(struct kreq *r)
{
	redisContext *rc = redis_get(&cf);
	redisReply *scan = NULL, *h;
	yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);
	yyjson_mut_val *root = yyjson_mut_obj(doc), *ent;
	char cursor[32] = "0", *out;
	size_t i, j, klen;

	yyjson_mut_doc_set_root(doc, root);
	do {
		if (rc == NULL || (scan = redisCommand(rc, "SCAN %s MATCH *:metadata "
		    "COUNT 200", cursor)) == NULL || scan->type != REDIS_REPLY_ARRAY ||
		    scan->elements != 2)
			break;
		snprintf(cursor, sizeof(cursor), "%s", scan->element[0]->str);
		for (i = 0; i < scan->element[1]->elements; i++) {
			const char *key = scan->element[1]->element[i]->str;

			klen = strlen(key) - strlen(":metadata");
			if ((h = redisCommand(rc, "HGETALL %s", key)) == NULL)
				break;
			ent = pim_org(doc, root, key, klen);
			ent = yyjson_mut_obj_get(ent, "text");
			for (j = 0; ent != NULL && h->type == REDIS_REPLY_ARRAY && j + 1 < h->elements; j += 2)
				yyjson_mut_obj_put(ent,
				    yyjson_mut_strcpy(doc, h->element[j]->str),
				    yyjson_mut_strcpy(doc, h->element[j + 1]->str));
			freeReplyObject(h);
		}
		freeReplyObject(scan);
		scan = NULL;
	} while (strcmp(cursor, "0") != 0);

	/* Merge both hashes under one organisation, as the editor expects. */
	snprintf(cursor, sizeof(cursor), "%s", "0");
	do {
		if (rc == NULL || (scan = redisCommand(rc, "SCAN %s MATCH *:images "
		    "COUNT 200", cursor)) == NULL || scan->type != REDIS_REPLY_ARRAY ||
		    scan->elements != 2)
			break;
		snprintf(cursor, sizeof(cursor), "%s", scan->element[0]->str);
		for (i = 0; i < scan->element[1]->elements; i++) {
			const char *key = scan->element[1]->element[i]->str;

			klen = strlen(key) - strlen(":images");
			if ((h = redisCommand(rc, "HGETALL %s", key)) == NULL)
				break;
			ent = pim_org(doc, root, key, klen);
			ent = yyjson_mut_obj_get(ent, "images");
			for (j = 0; ent != NULL && h->type == REDIS_REPLY_ARRAY && j + 1 < h->elements; j += 2)
				yyjson_mut_obj_put(ent,
				    yyjson_mut_strcpy(doc, h->element[j]->str),
				    yyjson_mut_strcpy(doc, h->element[j + 1]->str));
			freeReplyObject(h);
		}
		freeReplyObject(scan);
		scan = NULL;
	} while (strcmp(cursor, "0") != 0);

	if (scan != NULL)
		freeReplyObject(scan);
	if ((out = yyjson_mut_write(doc, 0, NULL)) != NULL)
		send_json(r, KHTTP_200, out);
	else
		send_err(r, KHTTP_500, "out of memory");
	free(out);
	yyjson_mut_doc_free(doc);
}

static void
dam_walk(yyjson_mut_doc *doc, yyjson_mut_val *images, yyjson_mut_val *fonts,
    const char *root, const char *rel, int depth)
{
	char path[1024], sub[512];
	struct dirent *de;
	struct stat st;
	const char *ext;
	DIR *d;

	snprintf(path, sizeof(path), "%s%s%s", root, *rel ? "/" : "", rel);
	if (depth > 4 || (d = opendir(path)) == NULL)
		return;
	while ((de = readdir(d)) != NULL) {
		if (de->d_name[0] == '.')
			continue;
		snprintf(sub, sizeof(sub), "%s%s%s", rel, *rel ? "/" : "", de->d_name);
		snprintf(path, sizeof(path), "%s/%s", root, sub);
		if (stat(path, &st) == -1 || !is_safe_relpath(sub))
			continue;
		if (S_ISDIR(st.st_mode)) {
			dam_walk(doc, images, fonts, root, sub, depth + 1);
			continue;
		}
		if ((ext = strrchr(de->d_name, '.')) == NULL)
			continue;
		if (strcasecmp(ext, ".png") == 0 || strcasecmp(ext, ".jpg") == 0 ||
		    strcasecmp(ext, ".jpeg") == 0)
			yyjson_mut_arr_add_strcpy(doc, images, sub);
		else if (strcasecmp(ext, ".ttf") == 0)
			yyjson_mut_arr_add_strcpy(doc, fonts, sub);
	}
	closedir(d);
}

static void
h_dam(struct kreq *r)
{
	yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);
	yyjson_mut_val *root = yyjson_mut_obj(doc);
	yyjson_mut_val *images = yyjson_mut_arr(doc), *fonts = yyjson_mut_arr(doc);
	char *out;

	yyjson_mut_doc_set_root(doc, root);
	yyjson_mut_obj_add_val(doc, root, "images", images);
	yyjson_mut_obj_add_val(doc, root, "fonts", fonts);
	yyjson_mut_obj_add_str(doc, root, "default_font",
	    conf_get(&cf, "default_font", ""));
	yyjson_mut_obj_add_str(doc, root, "date_format",
	    conf_get(&cf, "date_format", "%d-%m-%Y"));
	dam_walk(doc, images, fonts, conf_get(&cf, "dam_dir", "/var/www/dam"), "", 0);
	if ((out = yyjson_mut_write(doc, 0, NULL)) != NULL)
		send_json(r, KHTTP_200, out);
	else
		send_err(r, KHTTP_500, "out of memory");
	free(out);
	yyjson_mut_doc_free(doc);
}

/* Task 7: Lifecycle (retire, delete, unlink) */
static void
h_template_retire(struct kreq *r, PGconn *pg, const struct ident *id, const char *tid)
{
	if (!ident_has_role(id, &cf, "admin")) {
		send_err(r, KHTTP_403, "admin role required");
		return;
	}
	const char *p[] = { tid };
	db_do(pg, "UPDATE templates SET retired_at = NOW() WHERE id = $1::uuid", 1, p);
	send_json(r, KHTTP_200, "{\"ok\":true}");
}

static void
h_template_delete(struct kreq *r, PGconn *pg, const struct ident *id, const char *tid)
{
	if (!ident_has_role(id, &cf, "admin")) {
		send_err(r, KHTTP_403, "admin role required");
		return;
	}
	PGresult *res = db_q(pg, "SELECT COUNT(*) FROM documents WHERE template_id = $1::uuid", 1, (const char*[]){ tid });
	if (res != NULL && PQntuples(res) == 1) {
		int linked = atoi(PQgetvalue(res, 0, 0));
		PQclear(res);
		if (linked > 0) {
			char msg[128];
			snprintf(msg, sizeof(msg), "%d document%s still linked", linked, linked == 1 ? "" : "s");
			send_err(r, KHTTP_409, msg);
			return;
		}
	}
	char tmpl_path[700];
	snprintf(tmpl_path, sizeof(tmpl_path), "%s/templates/%s.pdf", conf_get(&cf, "data_dir", "/var/lib/signet"), tid);
	unlink(tmpl_path);
	db_do(pg, "DELETE FROM templates WHERE id = $1::uuid", 1, (const char*[]){ tid });
	send_json(r, KHTTP_200, "{\"ok\":true}");
}

static void
h_doc_unlink(struct kreq *r, PGconn *pg, const struct ident *id, const char *docid)
{
	if (!ident_has_role(id, &cf, "admin")) {
		send_err(r, KHTTP_403, "admin role required");
		return;
	}
	log_event(pg, docid, id->user, "UNLINKED", "");
	db_do(pg, "UPDATE documents SET template_id = NULL WHERE id = $1::uuid", 1, (const char*[]){ docid });
	send_json(r, KHTTP_200, "{\"ok\":true}");
}

static void
h_series_retire(struct kreq *r, PGconn *pg, const struct ident *id, const char *code)
{
	if (!ident_has_role(id, &cf, "admin")) {
		send_err(r, KHTTP_403, "admin role required");
		return;
	}
	const char *p[] = { code };
	db_do(pg, "UPDATE series SET retired_at = NOW() WHERE code = $1", 1, p);
	send_json(r, KHTTP_200, "{\"ok\":true}");
}

static int
queue_facsimile(const char *user, const char *key)
{
	redisContext *rc = redis_get(&cf);
	redisReply *reply;
	char job[256];
	int ok;

	if (rc == NULL)
		return -1;
	snprintf(job, sizeof(job), "{\"kind\":\"enrol\",\"user\":\"%s\",\"facsimile_id\":\"%s\"}", user, key);
	reply = redisCommand(rc, "LPUSH %s %s", conf_get(&cf, "queue", "queue:stamping"), job);
	if (reply == NULL) {
		redis_drop();
		return -1;
	}
	ok = reply->type == REDIS_REPLY_INTEGER;
	freeReplyObject(reply);
	return ok ? 0 : -1;
}

static void
h_facsimile_retry(struct kreq *r, PGconn *pg, const struct ident *id)
{
	const char *key = http_field_str(r, "facsimile_id");
	PGresult *res;

	if (!ident_has_role(id, &cf, "signer")) {
		send_err(r, KHTTP_403, "signer role required");
		return;
	}
	if (!is_uuid(key)) {
		send_err(r, KHTTP_400, "invalid facsimile reference");
		return;
	}
	res = db_q(pg, "SELECT id FROM facsimiles WHERE username=$1 AND id=$2::uuid AND enrol_error IS NULL",
	    2, (const char *[]){ id->user, key });
	if (res == NULL || PQntuples(res) != 1) {
		if (res != NULL)
			PQclear(res);
		send_err(r, KHTTP_409, "choose one of your pending signatures; invalid PNGs require a new upload");
		return;
	}
	PQclear(res);
	if (queue_facsimile(id->user, key) == -1)
		send_err(r, KHTTP_503, "could not queue activation; retry later");
	else
		send_json(r, KHTTP_200, "{\"ok\":true}");
}

static void
h_facsimile_upload(struct kreq *r, PGconn *pg, const struct ident *id, int admin)
{
	struct kpair *file = http_field(r, "file");
	const char *user = admin ? http_field_str(r, "user") : id->user;
	const char *label = http_field_str(r, "label"), *p[3];
	char inbox[1024] = "", key[37], body[80];
	PGresult *res = NULL;
	enum khttp failure = KHTTP_503;
	const char *message = "could not queue signature; retry later";
	size_t i;

	if (!ident_has_role(id, &cf, admin ? "admin" : "signer")) {
		send_err(r, KHTTP_403, admin ? "admin role required" : "signer role required");
		return;
	}
	if (!is_safe_name(user)) {
		send_err(r, KHTTP_400, "invalid user");
		return;
	}
	if (label == NULL && http_field(r, "label") == NULL)
		label = "Signature";
	if (label == NULL || !*label || strlen(label) > 80 || strspn(label, " ") == strlen(label)) {
		send_err(r, KHTTP_400, "signature label must be 1 to 80 bytes");
		return;
	}
	for (i = 0; label[i]; i++)
		if ((unsigned char)label[i] < 32 || label[i] == 127) {
			send_err(r, KHTTP_400, "signature label contains control characters");
			return;
		}
	if (file == NULL || file->valsz < 8 || file->valsz > 1048576 ||
	    memcmp(file->val, "\x89PNG\r\n\x1a\n", 8) != 0) {
		send_err(r, KHTTP_400, "PNG file required (max 1 MiB)");
		return;
	}
	p[0] = user;
	p[1] = id->user;
	p[2] = label;
	if (db_do(pg, "BEGIN", 0, NULL) == -1)
		goto fail;
	/* The enrol worker takes this same lock before observing queued work. */
	if (db_do(pg, "SELECT pg_advisory_xact_lock(hashtextextended($1,0))", 1, p) == -1)
		goto fail;
	res = db_q(pg, "WITH k AS (SELECT gen_random_uuid() AS id) "
	    "INSERT INTO facsimiles (id,storage_id,username,enrolled_by,label,is_default) "
	    "SELECT k.id,k.id,$1::varchar,$2::varchar,$3::varchar,false FROM k WHERE "
	    "(SELECT count(*) FROM facsimiles WHERE username=$1 AND enrol_error IS NULL)<32 RETURNING id::text", 3, p);
	if (res == NULL)
		goto fail;
	if (PQntuples(res) != 1) {
		failure = KHTTP_409;
		message = "limit of 32 ready or pending signature variants reached";
		goto fail;
	}
	snprintf(key, sizeof(key), "%s", PQgetvalue(res, 0, 0));
	snprintf(inbox, sizeof(inbox), "%s/%s.png",
	    conf_get(&cf, "sig_inbox", "/var/lib/signet/sig-inbox"), key);
	if (write_file(inbox, file->val, file->valsz, 0640) == -1)
		goto fail;
	if (queue_facsimile(user, key) == -1)
		goto fail;
	/* Queue visibility is safe: the worker waits for our transaction lock. */
	if (db_do(pg, "COMMIT", 0, NULL) == -1) {
		PQclear(res);
		send_err(r, KHTTP_503, "enrolment commit uncertain; reload your signature collection");
		return; /* Retain potentially committed input, never overwrite a variant. */
	}
	PQclear(res);
	snprintf(body, sizeof(body), "{\"ok\":true,\"id\":\"%s\"}", key);
	send_json(r, KHTTP_200, body);
	return;
fail:
	if (res != NULL)
		PQclear(res);
	db_do(pg, "ROLLBACK", 0, NULL);
	if (*inbox)
		unlink(inbox);
	send_err(r, failure, message);
}

static void
h_facsimile_default(struct kreq *r, PGconn *pg, const struct ident *id)
{
	const char *key = http_field_str(r, "facsimile_id");
	const char *p[] = { id->user, key };
	PGresult *res = NULL;

	if (!ident_has_role(id, &cf, "signer")) {
		send_err(r, KHTTP_403, "signer role required");
		return;
	}
	if (!is_uuid(key)) {
		send_err(r, KHTTP_400, "invalid facsimile reference");
		return;
	}
	if (db_do(pg, "BEGIN", 0, NULL) == -1 ||
	    db_do(pg, "SELECT pg_advisory_xact_lock(hashtextextended($1,0))", 1, p) == -1)
		goto fail;
	res = db_q(pg, "SELECT id FROM facsimiles WHERE username=$1 AND id=$2::uuid "
	    "AND enrolled_at IS NOT NULL FOR UPDATE", 2, p);
	if (res == NULL || PQntuples(res) != 1)
		goto fail;
	if (db_do(pg, "UPDATE facsimiles SET is_default=false WHERE username=$1 AND is_default", 1, p) == -1 ||
	    db_do(pg, "UPDATE facsimiles SET is_default=true WHERE username=$1 AND id=$2::uuid", 2, p) == -1 ||
	    log_event(pg, NULL, id->user, "FACSIMILE_DEFAULT", key) == -1 ||
	    db_do(pg, "COMMIT", 0, NULL) == -1)
		goto fail;
	PQclear(res);
	send_json(r, KHTTP_200, "{\"ok\":true}");
	return;
fail:
	if (res != NULL)
		PQclear(res);
	db_do(pg, "ROLLBACK", 0, NULL);
	send_err(r, KHTTP_409, "choose one of your enrolled signatures");
}

/* --- dispatch -------------------------------------------------------------- */

static void
dispatch(struct kreq *r)
{
	struct ident id;
	char buf[512], *seg[5];
	PGconn *pg;
	int n, get = r->method == KMETHOD_GET;

	ident_read(r, &cf, &id);
	if (id.user == NULL) {
		send_err(r, KHTTP_401, "no authenticated user");
		return;
	}
	if (!get && !http_post_ok(r)) {
		send_err(r, KHTTP_403, "POST with X-Requested-With: signet required");
		return;
	}
	if ((pg = db_get(&cf)) == NULL) {
		send_err(r, KHTTP_503, "database unavailable");
		return;
	}
	n = http_path(r, buf, sizeof(buf), seg, 5);

	if (n == 1 && get && strcmp(seg[0], "me") == 0)
		h_me(r, pg, &id);
	else if (n == 2 && !get && strcmp(seg[0], "me") == 0 && strcmp(seg[1], "facsimile") == 0)
		h_facsimile_upload(r, pg, &id, 0);
	else if (n == 3 && !get && strcmp(seg[0], "me") == 0 && strcmp(seg[1], "facsimile") == 0 && strcmp(seg[2], "default") == 0)
		h_facsimile_default(r, pg, &id);
	else if (n == 3 && !get && strcmp(seg[0], "me") == 0 && strcmp(seg[1], "facsimile") == 0 && strcmp(seg[2], "retry") == 0)
		h_facsimile_retry(r, pg, &id);
	else if (n == 1 && !get && strcmp(seg[0], "facsimiles") == 0)
		h_facsimile_upload(r, pg, &id, 1);
	else if (n == 1 && get && strcmp(seg[0], "pim") == 0)
		h_pim(r);
	else if (n == 1 && get && strcmp(seg[0], "dam") == 0)
		h_dam(r);
	else if (n == 1 && strcmp(seg[0], "templates") == 0)
		h_templates(r, pg, &id);
	else if (n == 3 && strcmp(seg[0], "templates") == 0 && is_uuid(seg[1])) {
		if (!get && strcmp(seg[2], "retire") == 0)
			h_template_retire(r, pg, &id, seg[1]);
		else if (!get && strcmp(seg[2], "delete") == 0)
			h_template_delete(r, pg, &id, seg[1]);
		else {
			send_err(r, KHTTP_404, "not found");
		}
	}
	else if (n == 1 && strcmp(seg[0], "series") == 0)
		h_series(r, pg, &id);
	else if (n == 3 && strcmp(seg[0], "series") == 0 && strcmp(seg[2], "retire") == 0) {
		if (!get)
			h_series_retire(r, pg, &id, seg[1]);
		else {
			send_err(r, KHTTP_404, "not found");
		}
	}
	else if (n == 1 && strcmp(seg[0], "docs") == 0)
		get ? h_docs_list(r, pg, &id) : h_doc_create(r, pg, &id);
	else if (n >= 2 && strcmp(seg[0], "docs") == 0 && is_uuid(seg[1])) {
		if (n == 2 && get)
			h_doc_get(r, pg, &id, seg[1]);
		else if (n == 4 && get && strcmp(seg[2], "file") == 0)
			h_doc_file(r, pg, &id, seg[1], seg[3]);
		else if (n == 3 && !get && strcmp(seg[2], "save") == 0)
			h_doc_save(r, pg, &id, seg[1]);
		else if (n == 3 && !get && strcmp(seg[2], "upload") == 0)
			h_doc_upload(r, pg, &id, seg[1]);
		else if (n == 3 && !get && strcmp(seg[2], "submit") == 0)
			h_doc_submit(r, pg, &id, seg[1]);
		else if (n == 3 && !get && strcmp(seg[2], "rerender") == 0)
			h_doc_rerender(r, pg, &id, seg[1]);
		else if (n == 3 && !get && strcmp(seg[2], "decide") == 0)
			h_doc_decide(r, pg, &id, seg[1]);
		else if (n == 3 && !get && strcmp(seg[2], "delete") == 0)
			h_doc_delete(r, pg, &id, seg[1]);
		else if (n == 3 && !get && strcmp(seg[2], "unlink") == 0)
			h_doc_unlink(r, pg, &id, seg[1]);
		else {
			send_err(r, KHTTP_404, "not found");
		}
	} else {
		send_err(r, KHTTP_404, "not found");
	}
}

int
main(void)
{
	static const char *const pages[] = { "index" };
	static const char *const fields[] = {
		"code", "comment", "decision", "doc_id", "facsimile_id", "file",
		"json", "label", "name", "offset", "pattern", "placement", "scope",
		"template_id", "total_size", "user"
	};
	const char *path = getenv("SIGNET_CONF");
	struct kfcgi *fcgi;
	struct kreq r;
	enum kcgi_err er;

	log_open("signet-api");
	if (conf_load(&cf, path ? path : CONF_PATH_DEFAULT) == -1) {
		log_err("cannot read configuration");
		return 1;
	}
	umask(007);
	if (khttp_fcgi_init(&fcgi, NULL, 0, pages, 1, 0) != KCGI_OK) {
		log_err("FastCGI initialization failed");
		return 1;
	}
	while ((er = khttp_fcgi_parse(fcgi, &r)) == KCGI_OK) {
		r.arg = &cf;
		if (http_keep_fields(&r, fields, sizeof(fields) / sizeof(fields[0])) == -1)
			send_err(&r, KHTTP_503, "request allocation failed");
		else
			dispatch(&r);
		khttp_free(&r);
		db_request_done();
	}
	if (er != KCGI_EXIT)
		log_err("FastCGI parse failed (code %d)", er);
	khttp_fcgi_free(fcgi);
	return er == KCGI_EXIT ? 0 : 1;
}
