/*
 * pim-api: deliberately tiny PIM.  PostgreSQL is the system of record,
 * Redis (HSET <org>:metadata <key> <value> for text,
 *        HSET <org>:images <key> <path> for images) is what signet reads.
 *
 *   GET  /attrs                         -> [{org_code, attr_key, attr_type, attr_value}]
 *   POST /attrs   org, key, type, value -> upsert (empty value deletes)
 *   POST /resync                        -> rebuild Redis from PostgreSQL
 *
 * Requires role.pim_admin for writes; any authenticated user may read.
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "conf.h"
#include "db.h"
#include "http.h"
#include "util.h"

static struct conf cf;

/* Keep the tiny catalog's post-commit mirror writes ordered across workers. */
static int
mirror_lock(PGconn *pg, int acquire)
{
	return db_do(pg, acquire ?
	    "SELECT pg_advisory_lock(hashtextextended('signet:pim-mirror',0))" :
	    "SELECT pg_advisory_unlock(hashtextextended('signet:pim-mirror',0))", 0, NULL);
}

static int
mirror(const char *org, const char *key, const char *type, const char *value)
{
	static const char script[] =
	    "for _,k in ipairs(KEYS) do "
	    "local t=redis.call('TYPE',k).ok; "
	    "if t~='none' and t~=(k==KEYS[1] and 'set' or 'hash') then "
	    "return redis.error_reply('invalid PIM mirror type') end end; "
	    "redis.call('HDEL',KEYS[2],ARGV[1]); redis.call('HDEL',KEYS[3],ARGV[1]); "
	    "if ARGV[3]~='' then redis.call('HSET',"
	    "ARGV[2]=='image' and KEYS[3] or KEYS[2],ARGV[1],ARGV[3]) end; "
	    "redis.call('SADD',KEYS[1],ARGV[4]); return 1";
	redisContext *rc = redis_get(&cf);
	redisReply *rep;
	int ok;

	if (rc == NULL)
		return -1;
	rep = redisCommand(rc, "EVAL %s 3 pim:orgs %s:metadata %s:images %s %s %s %s",
	    script, org, org, key, type, value ? value : "", org);
	ok = rep != NULL && rep->type == REDIS_REPLY_INTEGER && rep->integer == 1;
	if (!ok)
		log_err("PIM mirror command failed");
	if (rep != NULL)
		freeReplyObject(rep);
	else
		redis_drop();
	return ok ? 0 : -1;
}

static void
h_resync(struct kreq *r, PGconn *pg)
{
	static const char script[] =
	    "local rows=cjson.decode(ARGV[1]); local owned={}; "
	    "local function safe(s) return type(s)=='string' and #s<=50 "
	    "and string.sub(s,1,1)~='.' and string.match(s,'^[A-Za-z0-9._-]+$') end; "
	    "for _,org in ipairs(redis.call('SMEMBERS',KEYS[1])) do "
	    "if not safe(org) then return redis.error_reply('invalid PIM organisation') end; "
	    "owned[org]=true end; "
	    "for _,row in ipairs(rows) do "
	    "if not safe(row[1]) or not safe(row[2]) or type(row[4])~='string' "
	    "or (row[3]~='text' and row[3]~='image') then "
	    "return redis.error_reply('invalid PIM attribute') end; owned[row[1]]=true end; "
	    /* Validate everything before removing only this component's owned hashes. */
	    "for org in pairs(owned) do redis.call('DEL',org..':metadata',org..':images') end; "
	    "for _,row in ipairs(rows) do if row[4]~='' then redis.call('HSET',row[1].."
	    "(row[3]=='image' and ':images' or ':metadata'),row[2],row[4]) end end; "
	    "for org in pairs(owned) do redis.call('SADD',KEYS[1],org) end; return 1";
	PGresult *res;
	redisContext *rc;
	redisReply *rep = NULL;
	int bad = 1;

	if (mirror_lock(pg, 1) == -1) {
		send_err(r, KHTTP_500, "database error");
		return;
	}
	res = db_q(pg, "SELECT coalesce(json_agg(json_build_array(org_code, attr_key, "
	    "attr_type, attr_value)), '[]')::text FROM pim_attributes", 0, NULL);
	if (res == NULL) {
		mirror_lock(pg, 0);
		send_err(r, KHTTP_500, "database error");
		return;
	}
	if ((rc = redis_get(&cf)) != NULL) {
		rep = redisCommand(rc, "EVAL %s 1 pim:orgs %s", script, PQgetvalue(res, 0, 0));
		bad = rep == NULL || rep->type != REDIS_REPLY_INTEGER || rep->integer != 1;
		if (bad)
			log_err("PIM resync command failed");
		if (rep != NULL)
			freeReplyObject(rep);
		else
			redis_drop();
	}
	PQclear(res);
	if (mirror_lock(pg, 0) == -1)
		send_err(r, KHTTP_500, "database error");
	else if (bad)
		send_err(r, KHTTP_503, "redis unavailable");
	else
		send_json(r, KHTTP_200, "{\"ok\":true}");
}

static void
h_upsert(struct kreq *r, PGconn *pg)
{
	const char *p[4];
	int rc;

	p[0] = http_field_str(r, "org");
	p[1] = http_field_str(r, "key");
	p[2] = http_field_str(r, "type");
	p[3] = http_field_str(r, "value");
	if (!is_safe_name(p[0]) || !is_safe_name(p[1]) || strlen(p[0]) > 50 ||
	    strlen(p[1]) > 50 || p[2] == NULL || p[3] == NULL ||
	    (strcmp(p[2], "text") != 0 && strcmp(p[2], "image") != 0) ||
	    strlen(p[3]) > 500) {
		send_err(r, KHTTP_400, "org/key must be [A-Za-z0-9._-], type text|image");
		return;
	}
	if (mirror_lock(pg, 1) == -1) {
		send_err(r, KHTTP_500, "database error");
		return;
	}
	if (*p[3])
		rc = db_do(pg, "INSERT INTO pim_attributes (org_code, attr_key, attr_type, "
		    "attr_value) VALUES ($1, $2, $3, $4) ON CONFLICT (org_code, attr_key) "
		    "DO UPDATE SET attr_type = $3, attr_value = $4", 4, p);
	else
		rc = db_do(pg, "DELETE FROM pim_attributes WHERE org_code = $1 "
		    "AND attr_key = $2", 2, p);
	if (rc != -1)
		rc = mirror(p[0], p[1], p[2], p[3]) == -1 ? 1 : 0;
	if (mirror_lock(pg, 0) == -1)
		rc = -1;
	if (rc == -1)
		send_err(r, KHTTP_500, "database error");
	else if (rc == 1)
		send_err(r, KHTTP_503, "saved, but Redis is down: run resync later");
	else
		send_json(r, KHTTP_200, "{\"ok\":true}");
}

static void
dispatch(struct kreq *r)
{
	struct ident id;
	char buf[256], *seg[2];
	PGconn *pg;
	PGresult *res;
	int n;

	ident_read(r, &cf, &id);
	if (id.user == NULL) {
		send_err(r, KHTTP_401, "no authenticated user");
		return;
	}
	if ((pg = db_get(&cf)) == NULL) {
		send_err(r, KHTTP_503, "database unavailable");
		return;
	}
	n = http_path(r, buf, sizeof(buf), seg, 2);
	if (n == 1 && r->method == KMETHOD_GET && strcmp(seg[0], "me") == 0) {
		snprintf(buf, sizeof(buf), "{\"user\":\"%s\",\"roles\":{\"pim_admin\":%s}}",
		    id.user, ident_has_role(&id, &cf, "pim_admin") ? "true" : "false");
		send_json(r, KHTTP_200, buf);
		return;
	}
	if (n == 1 && r->method == KMETHOD_GET && strcmp(seg[0], "attrs") == 0) {
		res = db_q(pg, "SELECT coalesce(json_agg(t), '[]')::text FROM ("
		    "SELECT org_code, attr_key, attr_type, attr_value FROM pim_attributes "
		    "ORDER BY org_code, attr_key) t", 0, NULL);
		if (res == NULL) {
			send_err(r, KHTTP_500, "database error");
		} else {
			send_json(r, KHTTP_200, PQgetvalue(res, 0, 0));
			PQclear(res);
		}
		return;
	}
	if (!http_post_ok(r) || !ident_has_role(&id, &cf, "pim_admin")) {
		send_err(r, KHTTP_403, "pim_admin role required");
		return;
	}
	if (n == 1 && strcmp(seg[0], "attrs") == 0)
		h_upsert(r, pg);
	else if (n == 1 && strcmp(seg[0], "resync") == 0)
		h_resync(r, pg);
	else {
		send_err(r, KHTTP_404, "not found");
	}
}

int
main(void)
{
	static const char *const pages[] = { "index" };
	static const char *const fields[] = { "org", "key", "type", "value" };
	const char *path = getenv("SIGNET_CONF");
	struct kfcgi *fcgi;
	struct kreq r;
	enum kcgi_err er;

	log_open("pim-api");
	if (conf_load(&cf, path ? path : CONF_PATH_DEFAULT) == -1) {
		log_err("cannot read configuration");
		return 1;
	}
	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;
}
