/*
 * signetd: serial render worker. Jobs stay in :processing until the database
 * outcome is committed. A locked document row serialises rendering with API
 * transitions; immutable render inputs make replay safe after a failed commit.
 */
#include <sys/stat.h>

#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include <png.h>

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

static struct conf cf;
static char queue[128], processing[160];

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 *action, const char *detail)
{
	const char *p[] = { id, action, detail };

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

static int
png_get_dimensions(const char *path, int *width, int *height)
{
	png_image png;
	void *pixels;
	int rv = -1;

	memset(&png, 0, sizeof(png));
	png.version = PNG_IMAGE_VERSION;
	if (!png_image_begin_read_from_file(&png, path))
		return -1;
	png.format = PNG_FORMAT_RGBA;
	if (png.width == 0 || png.height == 0 || (uint64_t)png.width * png.height > 4000000) {
		png_image_free(&png);
		return -1;
	}
	pixels = malloc(PNG_IMAGE_SIZE(png));
	if (pixels != NULL && png_image_finish_read(&png, NULL, pixels, 0, NULL)) {
		*width = png.width;
		*height = png.height;
		rv = 0;
	}
	free(pixels);
	png_image_free(&png);
	return rv;
}

/* Enrol jobs have no document id or render sequence. */
static int
process_enrol(PGconn *pg, const char *user, const char *variant)
{
	char inbox[1024], sig[1024], tmp[1040], w[16], h[16], key[37], name[65], sha[65];
	const char *p[] = { user, variant, w, h, sha };
	PGresult *res;
	int width, height, fd = -1, rv = -1;

	if (db_do(pg, "BEGIN", 0, NULL) == -1)
		return -1;
	if (db_do(pg, "SELECT pg_advisory_xact_lock(hashtextextended($1,0))", 1, p) == -1)
		goto out;
	res = db_q(pg, "SELECT id::text,enrolled_at,storage_id::text FROM facsimiles WHERE username=$1 "
	    "AND (($2::uuid IS NULL AND storage_id IS NULL) OR id=$2::uuid) FOR UPDATE", 2, p);
	if (res == NULL)
		goto out;
	if (PQntuples(res) == 0 || !PQgetisnull(res, 0, 1)) {
		PQclear(res);
		rv = db_do(pg, "COMMIT", 0, NULL);
		goto out;
	}
	snprintf(key, sizeof(key), "%s", PQgetvalue(res, 0, 0));
	snprintf(name, sizeof(name), "%s", PQgetisnull(res, 0, 2) ? user : PQgetvalue(res, 0, 2));
	PQclear(res);
	if (!is_uuid(key) || !is_safe_name(name))
		goto out;
	p[1] = key;
	snprintf(inbox, sizeof(inbox), "%s/%s.png",
	    conf_get(&cf, "sig_inbox", "/var/lib/signet/sig-inbox"), name);
	snprintf(sig, sizeof(sig), "%s/%s.png",
	    conf_get(&cf, "sig_dir", "/var/lib/signatures"), name);
	snprintf(tmp, sizeof(tmp), "%s.tmp", sig);
	/* Keep the inbox until commit, so a failed database update is replayable. */
	if (png_get_dimensions(inbox, &width, &height) == -1) {
		if (access(inbox, F_OK) == -1 && errno != ENOENT)
			goto out;
		if (db_do(pg, "UPDATE facsimiles SET enrol_error='PNG decoding failed; upload a new variant', "
		    "is_default=false WHERE id=$2::uuid AND username=$1", 2, p) == -1 ||
		    log_event(pg, NULL, "ENROL_FAILED", key) == -1 ||
		    db_do(pg, "COMMIT", 0, NULL) == -1)
			goto out;
		unlink(inbox);
		return 0;
	}
	if (copy_file(inbox, tmp) == -1 || chmod(tmp, 0600) == -1 ||
	    sha256_file(tmp, sha) == -1 || (fd = open(tmp, O_RDONLY)) == -1 || fsync(fd) == -1)
		goto out;
	close(fd);
	fd = -1;
	if (rename(tmp, sig) == -1 ||
	    (fd = open(conf_get(&cf, "sig_dir", "/var/lib/signatures"), O_RDONLY | O_DIRECTORY)) == -1 ||
	    fsync(fd) == -1)
		goto out;
	close(fd);
	fd = -1;
	snprintf(w, sizeof(w), "%d", width);
	snprintf(h, sizeof(h), "%d", height);
	if (db_do(pg, "UPDATE facsimiles SET is_default=false WHERE username=$1 AND id<>$2::uuid "
	    "AND is_default AND enrolled_at IS NULL", 2, p) == -1 ||
	    db_do(pg, "UPDATE facsimiles SET enrolled_at=CURRENT_TIMESTAMP,width=$3::int,height=$4::int, "
	    "sha256=$5,enrol_error=NULL,is_default=NOT EXISTS(SELECT 1 FROM facsimiles f WHERE "
	    "f.username=$1 AND f.is_default AND f.id<>$2::uuid) WHERE id=$2::uuid AND username=$1", 5, p) == -1 ||
	    log_event(pg, NULL, "ENROLLED", key) == -1 ||
	    db_do(pg, "COMMIT", 0, NULL) == -1)
		goto out;
	unlink(inbox);
	rv = 0;
out:
	if (fd != -1)
		close(fd);
	if (rv == -1)
		db_do(pg, "ROLLBACK", 0, NULL);
	return rv;
}

static yyjson_doc *
load_snapshot(const char *id, const char *key, const char *json,
    struct render_ctx *cx, char assets[1024], char *err, size_t errsz)
{
	yyjson_doc *doc;
	yyjson_val *root;
	char name[64];

	if (!is_uuid(key) || (doc = yyjson_read(json, strlen(json), 0)) == NULL) {
		snprintf(err, errsz, "revision has no submit-time snapshot; never rebuild from live inputs");
		return NULL;
	}
	root = yyjson_doc_get_root(doc);
	snprintf(name, sizeof(name), "snapshot-%s", key);
	doc_path(assets, 1024, id, name);
	if (snapshot_verify(root, assets, err, errsz) == -1 ||
	    !yyjson_is_obj(yyjson_obj_get(root, "layout")) ||
	    !yyjson_is_str(yyjson_obj_get(root, "default_font")) ||
	    !yyjson_is_str(yyjson_obj_get(root, "date_format"))) {
		yyjson_doc_free(doc);
		return NULL;
	}
	memset(cx, 0, sizeof(*cx));
	cx->asset_dir = assets;
	cx->default_font = yyjson_get_str(yyjson_obj_get(root, "default_font"));
	cx->date_format = yyjson_get_str(yyjson_obj_get(root, "date_format"));
	return doc;
}

static int
render_pair(const char *id, const char *snapshot_txt, const char *key,
    const char *serial, const char *date, const char *candidate,
    char *err, size_t errsz)
{
	struct render_ctx cx;
	char dir[512], src[600], tmp[740], proof[600], copy[740], assets[1024];
	char name[64], cached[700];
	yyjson_doc *doc;
	int rv = -1;

	doc_path(dir, sizeof(dir), id, NULL);
	doc_path(src, sizeof(src), id, "source.pdf");
	doc_path(proof, sizeof(proof), id, "proof.pdf");
	doc = load_snapshot(id, key, snapshot_txt, &cx, assets, err, errsz);
	if (doc == NULL)
		return -1;
	cx.serial = serial;
	cx.doc_date = date;
	cx.tmpdir = dir;
	snprintf(name, sizeof(name), "proof-%s.pdf", key);
	doc_path(cached, sizeof(cached), id, name);
	snprintf(tmp, sizeof(tmp), "%s.tmp", cached);
	/* A successful flatten survives database failure and stamp retries. */
	if (!file_exists(cached)) {
		if (render_stamp(&cx, yyjson_obj_get(yyjson_doc_get_root(doc), "layout"),
		    src, tmp, err, errsz) == -1 || chmod(tmp, 0440) == -1 || rename(tmp, cached) == -1)
			goto out;
	}
	snprintf(tmp, sizeof(tmp), "%s.tmp", proof);
	snprintf(copy, sizeof(copy), "%s.tmp", candidate);
	unlink(tmp);
	/* Public proof links the revision cache; stamped input is byte-identical. */
	if (link(cached, tmp) == 0 && copy_file(cached, copy) == 0 &&
	    rename(tmp, proof) == 0 && rename(copy, candidate) == 0)
		rv = 0;
out:
	if (rv == -1 && !*err)
		snprintf(err, errsz, "could not publish render output");
	unlink(tmp);
	if (rv == -1) {
		snprintf(copy, sizeof(copy), "%s.tmp", candidate);
		unlink(copy);
	}
	yyjson_doc_free(doc);
	return rv;
}

static int
render_decision(PGconn *pg, const char *id, const char *revision,
    const char *base, const char *candidate, char *err, size_t errsz)
{
	const char *p[] = { id, revision };
	PGresult *res;
	yyjson_doc *doc = NULL;
	yyjson_val *pl, *coords;
	struct render_ctx cx;
	char png[1024], dir[600], tmp[700], sha[65];
	double x, y, w, h, rw, rh;
	int page, rv = -1;

	/* Sign jobs follow advancement; release keeps the final party current. */
	res = db_q(pg, "SELECT x.signer, x.placement::text, f.enrolled_at, f.storage_id::text, f.sha256 "
	    "FROM doc_decisions x JOIN documents d ON d.id = x.doc_id "
	    "LEFT JOIN facsimiles f ON f.username = x.signer AND "
	    "(f.id=x.facsimile_id OR (x.facsimile_id IS NULL AND f.storage_id IS NULL)) "
	    "WHERE x.doc_id = $1 AND x.revision = $2::int "
	    "AND x.party = CASE WHEN d.render_kind = 'release' THEN d.current_party "
	    "ELSE d.current_party - 1 END AND x.decision = 'SIGNOFF'", 2, p);
	if (res == NULL)
		return -2;
	if (PQntuples(res) != 1 || !is_safe_name(PQgetvalue(res, 0, 0))) {
		snprintf(err, errsz, "signed party has no enrolled facsimile or placement");
		goto out;
	}
	if (PQgetisnull(res, 0, 1)) {
		snprintf(tmp, sizeof(tmp), "%s.tmp", candidate);
		if (copy_file(base, tmp) == 0 && rename(tmp, candidate) == 0)
			rv = 0;
		else
			snprintf(err, errsz, "could not copy check-only body");
		unlink(tmp);
		goto out;
	}
	if (PQgetisnull(res, 0, 2)) {
		snprintf(err, errsz, "facsimile is not enrolled");
		goto out;
	}
	doc = yyjson_read(PQgetvalue(res, 0, 1), strlen(PQgetvalue(res, 0, 1)), 0);
	if (doc == NULL) {
		snprintf(err, errsz, "invalid signature placement");
		goto out;
	}
	pl = yyjson_doc_get_root(doc);
	coords = yyjson_obj_get(pl, "coords");
	page = yyjson_get_int(yyjson_obj_get(pl, "page"));
	rw = yyjson_get_num(yyjson_obj_get(pl, "ref_w"));
	rh = yyjson_get_num(yyjson_obj_get(pl, "ref_h"));
	x = yyjson_get_num(yyjson_arr_get(coords, 0));
	y = yyjson_get_num(yyjson_arr_get(coords, 1));
	w = yyjson_get_num(yyjson_arr_get(coords, 2)) - x;
	h = yyjson_get_num(yyjson_arr_get(coords, 3)) - y;
	if (rw <= 0 || rh <= 0 || x < 0 || y < 0 || w <= 0 || h <= 0 ||
	    x + w > rw || y + h > rh || page < 1) {
		snprintf(err, errsz, "invalid signature page or coordinates");
		goto out;
	}
	if (!PQgetisnull(res, 0, 3) && !is_uuid(PQgetvalue(res, 0, 3))) {
		snprintf(err, errsz, "invalid private facsimile reference");
		goto out;
	}
	snprintf(png, sizeof(png), "%s/%s.png",
	    conf_get(&cf, "sig_dir", "/var/lib/signatures"),
	    PQgetisnull(res, 0, 3) ? PQgetvalue(res, 0, 0) : PQgetvalue(res, 0, 3));
	if (!PQgetisnull(res, 0, 4) && (sha256_file(png, sha) == -1 || strcmp(sha, PQgetvalue(res, 0, 4)) != 0)) {
		snprintf(err, errsz, "enrolled facsimile is missing or damaged");
		goto out;
	}
	doc_path(dir, sizeof(dir), id, NULL);
	snprintf(tmp, sizeof(tmp), "%s.tmp", candidate);
	memset(&cx, 0, sizeof(cx));
	cx.tmpdir = dir;
	rv = render_sign(&cx, base, tmp, png, page, x, y, w, h, rw, rh, err, errsz);
	if (rv == 0 && (chmod(tmp, 0640) == -1 || rename(tmp, candidate) == -1)) {
		snprintf(err, errsz, "could not publish signature output");
		rv = -1;
	}
	unlink(tmp);
out:
	yyjson_doc_free(doc);
	PQclear(res);
	return rv;
}

static int
release_document(PGconn *pg, const char *id, const char *body, char sha[65],
    const char *snapshot_txt, const char *key, char *err, size_t errsz)
{
	const char *p[] = { id }, **lines;
	struct render_ctx cx;
	PGresult *res;
	char dir[600], tmp[700], final[700], body_sha[65], assets[1024];
	yyjson_doc *snapshot;
	int i, n, rv = -1;

	if (sha256_file(body, body_sha) == -1) {
		snprintf(err, errsz, "could not hash the signed body");
		return -1;
	}
	/* Included in the audit only if the same completion transaction commits. */
	if (log_event(pg, id, "RELEASED", body_sha) == -1)
		return -2;
	res = db_q(pg, "SELECT line FROM ("
	    "SELECT 0 AS bucket, 0::bigint AS event_id, 'Document ID: ' || id AS line FROM documents WHERE id=$1 "
	    "UNION ALL SELECT 1, 0, 'Serial: ' || coalesce(serial, '-') FROM documents WHERE id=$1 "
	    "UNION ALL SELECT 2, 0, 'Title: ' || title FROM documents WHERE id=$1 "
	    "UNION ALL SELECT 3, 0, 'Organisation: ' || coalesce(org_code, '-') FROM documents WHERE id=$1 "
	    "UNION ALL SELECT 4, 0, 'Drafter: ' || drafter_user FROM documents WHERE id=$1 "
	    "UNION ALL SELECT 5, 0, 'Full event log (all revisions):' "
	    "UNION ALL SELECT 6, id, to_char(at, 'YYYY-MM-DD HH24:MI:SS TZ') || ' | ' || "
	    "actor || ' | ' || action || ' | ' || detail FROM doc_events WHERE doc_id=$1 "
	    ") audit ORDER BY bucket, event_id", 1, p);
	if (res == NULL)
		return -2;
	n = PQntuples(res);
	lines = malloc(((size_t)n + 3) * sizeof(*lines));
	if (lines == NULL) {
		snprintf(err, errsz, "could not allocate audit lines");
		PQclear(res);
		return -1;
	}
	for (i = 0; i < n; i++)
		lines[i] = PQgetvalue(res, i, 0);
	lines[n++] = "SHA-256 of the signed body before the audit pages:";
	lines[n++] = body_sha;
	lines[n++] = "Signature images are facsimiles, not cryptographic signatures.";
	doc_path(dir, sizeof(dir), id, NULL);
	doc_path(tmp, sizeof(tmp), id, "final.pdf.tmp");
	doc_path(final, sizeof(final), id, "final.pdf");
	snapshot = load_snapshot(id, key, snapshot_txt, &cx, assets, err, errsz);
	if (snapshot == NULL) {
		free(lines);
		PQclear(res);
		return -1;
	}
	cx.tmpdir = dir;
	if (render_release(&cx, body, tmp, lines, n, err, errsz) == 0) {
		if (sha256_file(tmp, sha) == 0 && chmod(tmp, 0640) == 0 && rename(tmp, final) == 0)
			rv = 0;
		else
			snprintf(err, errsz, "could not publish final copy");
	}
	unlink(tmp);
	yyjson_doc_free(snapshot);
	free(lines);
	PQclear(res);
	return rv;
}

/* A committed render file is never overwritten, even when its job is replayed. */
static int
publish_stamped(const char *id, const char *candidate)
{
	char tmp[700], dst[700];

	doc_path(tmp, sizeof(tmp), id, "stamped.pdf.tmp");
	doc_path(dst, sizeof(dst), id, "stamped.pdf");
	unlink(tmp);
	return link(candidate, tmp) == 0 && rename(tmp, dst) == 0 ? 0 : -1;
}

static int
cleanup_release(const char *id, int seq)
{
	char path[700], name[64];

	doc_path(path, sizeof(path), id, "stamped.pdf");
	if (unlink(path) == -1 && errno != ENOENT)
		return -1;
	snprintf(name, sizeof(name), "render-%d.pdf", seq);
	doc_path(path, sizeof(path), id, name);
	return unlink(path) == 0 || errno == ENOENT ? 0 : -1;
}

/* 0 acknowledges an invalid/stale job or a committed outcome; -1 retries. */
static int
process(const char *payload)
{
	PGconn *pg;
	PGresult *res = NULL, *updated = NULL;
	yyjson_doc *job;
	yyjson_val *root, *revision, *sequence;
	const char *id, *kind, *user, *variant, *action, *p[5];
	char revbuf[16], seqbuf[16], err[512] = "", sha[65] = "";
	char name[64], base[700], candidate[700];
	int seq, previous = 0, rv = -1, rendered;

	if ((job = yyjson_read(payload, strlen(payload), 0)) == NULL)
		return 0;
	root = yyjson_doc_get_root(job);
	kind = yyjson_get_str(yyjson_obj_get(root, "kind"));
	id = yyjson_get_str(yyjson_obj_get(root, "doc_id"));
	user = yyjson_get_str(yyjson_obj_get(root, "user"));
	revision = yyjson_obj_get(root, "revision");
	sequence = yyjson_obj_get(root, "seq");
	if (kind != NULL && strcmp(kind, "enrol") == 0) {
		variant = yyjson_get_str(yyjson_obj_get(root, "facsimile_id"));
		if (!is_safe_name(user) || (yyjson_obj_get(root, "facsimile_id") != NULL && !is_uuid(variant)))
			goto invalid;
		pg = db_get(&cf);
		rv = pg == NULL ? -1 : process_enrol(pg, user, variant);
		goto done;
	}
	if (kind == NULL || (strcmp(kind, "stamp") != 0 && strcmp(kind, "sign") != 0 &&
	    strcmp(kind, "release") != 0) || !is_uuid(id) ||
	    !yyjson_is_int(revision) || yyjson_get_sint(revision) < 1 ||
	    yyjson_get_sint(revision) > INT_MAX || !yyjson_is_int(sequence) ||
	    yyjson_get_sint(sequence) < 1 || yyjson_get_sint(sequence) > INT_MAX)
		goto invalid;
	seq = yyjson_get_int(sequence);
	snprintf(revbuf, sizeof(revbuf), "%d", yyjson_get_int(revision));
	snprintf(seqbuf, sizeof(seqbuf), "%d", seq);
	p[0] = id;
	p[1] = revbuf;
	p[2] = seqbuf;
	p[3] = kind;
	if ((pg = db_get(&cf)) == NULL || db_do(pg, "BEGIN", 0, NULL) == -1)
		goto done;
	/* Hold the row through filesystem publication and database completion. */
	res = db_q(pg, "SELECT snapshot_json::text, serial, doc_date::text, snapshot_id::text, "
	    "rendered_seq FROM documents WHERE id = $1 AND revision = $2::int "
	    "AND render_seq = $3::int AND render_kind = $4 AND status = 'PENDING' "
	    "AND rendered_seq < render_seq AND render_error IS NULL FOR UPDATE", 4, p);
	if (res == NULL)
		goto rollback;
	if (PQntuples(res) == 0) {
		/* A crash after release commit can precede filesystem cleanup/LREM. */
		if (strcmp(kind, "release") == 0) {
			updated = db_q(pg, "SELECT id FROM documents WHERE id=$1 AND revision=$2::int "
			    "AND rendered_seq=$3::int AND render_seq=$3::int AND status='RELEASED'", 3, p);
			if (updated == NULL)
				goto rollback;
		}
		rv = db_do(pg, "COMMIT", 0, NULL);
		if (rv == 0 && updated != NULL && PQntuples(updated) == 1)
			rv = cleanup_release(id, seq);
		goto rollback;
	}
	previous = atoi(PQgetvalue(res, 0, 4));
	snprintf(name, sizeof(name), "render-%d.pdf", previous);
	doc_path(base, sizeof(base), id, name);
	snprintf(name, sizeof(name), "render-%d.pdf", seq);
	doc_path(candidate, sizeof(candidate), id, name);
	if (strcmp(kind, "stamp") == 0) {
		rendered = render_pair(id, PQgetvalue(res, 0, 0), PQgetvalue(res, 0, 3),
		    PQgetisnull(res, 0, 1) ? NULL : PQgetvalue(res, 0, 1),
		    PQgetvalue(res, 0, 2), candidate, err, sizeof(err));
		action = rendered == 0 ? "STAMPED" : "STAMP_FAILED";
	} else if (strcmp(kind, "sign") == 0) {
		rendered = render_decision(pg, id, revbuf, base, candidate, err, sizeof(err));
		if (rendered == -2)
			goto rollback;
		action = rendered == 0 ? "SIGNED" : "SIGN_FAILED";
	} else {
		if (db_do(pg, "SAVEPOINT release_output", 0, NULL) == -1)
			goto rollback;
		rendered = render_decision(pg, id, revbuf, base, candidate, err, sizeof(err));
		if (rendered == 0)
			rendered = release_document(pg, id, candidate, sha,
			    PQgetvalue(res, 0, 0), PQgetvalue(res, 0, 3), err, sizeof(err));
		if (rendered == -2)
			goto rollback;
		if (rendered != 0 && db_do(pg, "ROLLBACK TO SAVEPOINT release_output", 0, NULL) == -1)
			goto rollback;
		action = rendered == 0 ? NULL : "RELEASE_FAILED";
	}
	if (rendered == 0 && strcmp(kind, "release") != 0 && publish_stamped(id, candidate) == -1) {
		rendered = -1;
		snprintf(err, sizeof(err), "could not publish stamped copy");
		action = strcmp(kind, "stamp") == 0 ? "STAMP_FAILED" : "SIGN_FAILED";
	}
	p[4] = rendered == 0 && strcmp(kind, "release") == 0 ? sha : err;
	updated = db_q(pg, rendered == 0 && strcmp(kind, "release") == 0
	    ? "UPDATE documents SET status='RELEASED', rendered_seq=$3::int, render_error=NULL, "
	      "final_sha256=$5, released_at=CURRENT_TIMESTAMP WHERE id=$1 "
	      "AND revision=$2::int AND render_kind=$4 RETURNING id"
	    : rendered == 0
	    ? "UPDATE documents SET rendered_seq = $3::int, render_error = NULL "
	      "WHERE id = $1 AND revision = $2::int AND render_kind = $4 RETURNING id"
	    : "UPDATE documents SET render_error = $5 WHERE id = $1 "
	      "AND revision = $2::int AND render_seq = $3::int AND render_kind = $4 RETURNING id",
	    rendered == 0 && strcmp(kind, "release") != 0 ? 4 : 5, p);
	if (updated == NULL || PQntuples(updated) != 1 ||
	    (action != NULL && log_event(pg, id, action, err) == -1) || db_do(pg, "COMMIT", 0, NULL) == -1)
		goto rollback;
	/* Only the current immutable base is needed after a committed outcome. */
	if (rendered == 0 && previous > 0)
		unlink(base);
	if (rendered == 0 && strcmp(kind, "release") == 0 && cleanup_release(id, seq) == -1)
		goto rollback;
	if (rendered != 0) {
		unlink(candidate);
		fprintf(stderr, "signetd: %s: %s\n", id, err);
	}
	rv = 0;
rollback:
	if (rv == -1)
		db_do(pg, "ROLLBACK", 0, NULL);
done:
	if (res != NULL)
		PQclear(res);
	if (updated != NULL)
		PQclear(updated);
	yyjson_doc_free(job);
	return rv;
invalid:
	fprintf(stderr, "signetd: dropping invalid render job\n");
	rv = 0;
	goto done;
}

static int
recover(redisContext *rc)
{
	redisReply *r;
	int more;

	do {
		r = redisCommand(rc, "RPOPLPUSH %s %s", processing, queue);
		if (r == NULL || (r->type != REDIS_REPLY_STRING && r->type != REDIS_REPLY_NIL)) {
			if (r != NULL)
				freeReplyObject(r);
			return -1;
		}
		more = r->type == REDIS_REPLY_STRING;
		freeReplyObject(r);
	} while (more);
	return 0;
}

int
main(int argc, char *argv[])
{
	const char *path = CONF_PATH_DEFAULT;
	redisContext *rc;
	redisReply *r, *d;
	int c, ready = 0;

	while ((c = getopt(argc, argv, "c:")) != -1)
		if (c == 'c')
			path = optarg;
	if (conf_load(&cf, path) == -1) {
		fprintf(stderr, "signetd: cannot read %s\n", path);
		return 1;
	}
	snprintf(queue, sizeof(queue), "%s", conf_get(&cf, "queue", "queue:stamping"));
	snprintf(processing, sizeof(processing), "%s:processing", queue);
	umask(027);
	for (;;) {
		if ((rc = redis_get(&cf)) == NULL) {
			ready = 0;
			sleep(2);
			continue;
		}
		/* Also recover after a lost acknowledgement or Redis reconnection. */
		if (!ready && recover(rc) == -1) {
			redis_drop();
			sleep(2);
			continue;
		}
		ready = 1;
		r = redisCommand(rc, "BRPOPLPUSH %s %s 30", queue, processing);
		if (r == NULL || r->type == REDIS_REPLY_ERROR) {
			if (r != NULL)
				freeReplyObject(r);
			redis_drop();
			ready = 0;
			continue;
		}
		if (r->type == REDIS_REPLY_STRING) {
			if (process(r->str) == 0) {
				d = redisCommand(rc, "LREM %s 1 %b", processing, r->str, r->len);
				if (d == NULL || d->type != REDIS_REPLY_INTEGER || d->integer != 1)
					ready = 0;
			} else {
				d = redisCommand(rc, "RPOPLPUSH %s %s", processing, queue);
				if (d == NULL || d->type != REDIS_REPLY_STRING)
					ready = 0;
				sleep(5);
			}
			if (d != NULL)
				freeReplyObject(d);
		}
		freeReplyObject(r);
	}
}
