#include <sys/stat.h>

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

#include "snapshot.h"
#include "util.h"

#define MAX_ASSETS 201 /* 200 imprints plus the audit font. */
#define MAX_ASSET_BYTES (16u * 1024 * 1024) /* Aggregate frozen inputs, streamed. */

struct asset {
	char ref[1024], name[32];
};

/* Open every DAM component without following symlinks, including directories. */
static int
open_asset(const char *dam, const char *ref)
{
	char path[1024], *part, *next;
	int dir, fd;

	if (!is_safe_relpath(ref) || strlen(ref) >= sizeof(path))
		return -1;
	strcpy(path, ref);
	if ((dir = open(dam, O_RDONLY | O_DIRECTORY)) == -1)
		return -1;
	for (part = path; (next = strchr(part, '/')) != NULL; part = next + 1) {
		*next = '\0';
		fd = openat(dir, part, O_RDONLY | O_DIRECTORY | O_NOFOLLOW);
		close(dir);
		if (fd == -1)
			return -1;
		dir = fd;
	}
	fd = openat(dir, part, O_RDONLY | O_NOFOLLOW | O_NONBLOCK);
	close(dir);
	return fd;
}

static int
freeze_asset(const struct conf *cf, const char *ref, const char *dir,
    struct asset assets[MAX_ASSETS], int *count, size_t *total, yyjson_mut_doc *doc,
    yyjson_mut_val *files, char name[32])
{
	char dest[1200], buf[16384], hash[65];
	struct stat before, after;
	yyjson_mut_val *file;
	ssize_t n, written;
	int i, in, out = -1, rv = -1;
	size_t copied = 0;

	for (i = 0; i < *count; i++)
		if (strcmp(assets[i].ref, ref) == 0) {
			strcpy(name, assets[i].name);
			return 0;
		}
	if (*count == MAX_ASSETS || strlen(ref) >= sizeof(assets[0].ref))
		return -1;
	in = open_asset(conf_get(cf, "dam_dir", "/var/www/dam"), ref);
	if (in == -1)
		return -1;
	if (fstat(in, &before) == -1 || !S_ISREG(before.st_mode) ||
	    before.st_size < 1 || (uint64_t)before.st_size > MAX_ASSET_BYTES - *total)
		goto out;
	snprintf(name, 32, "asset-%d", *count);
	snprintf(dest, sizeof(dest), "%s/%s", dir, name);
	if ((out = open(dest, O_WRONLY | O_CREAT | O_EXCL, 0640)) == -1)
		goto out;
	while ((n = read(in, buf, sizeof(buf))) != 0) {
		if (n == -1) {
			if (errno == EINTR)
				continue;
			goto out;
		}
		if ((size_t)n > (size_t)before.st_size - copied)
			goto out;
		copied += (size_t)n;
		for (written = 0; written < n;) {
			ssize_t step = write(out, buf + written, (size_t)(n - written));
			if (step == -1 && errno == EINTR)
				continue;
			if (step <= 0)
				goto out;
			written += step;
		}
	}
	/* Reject in-place edits during the copy; atomic replacement keeps this fd stable. */
	if (fstat(in, &after) == -1 || copied != (size_t)before.st_size || before.st_size != after.st_size ||
	    before.st_mtim.tv_sec != after.st_mtim.tv_sec ||
	    before.st_mtim.tv_nsec != after.st_mtim.tv_nsec ||
	    before.st_ctim.tv_sec != after.st_ctim.tv_sec ||
	    before.st_ctim.tv_nsec != after.st_ctim.tv_nsec ||
	    fchmod(out, 0440) == -1 || fsync(out) == -1)
		goto out;
	if (close(out) == -1) {
		out = -1;
		goto out;
	}
	out = -1;
	if (sha256_file(dest, hash) == -1)
		goto out;
	file = yyjson_mut_obj(doc);
	if (file == NULL || !yyjson_mut_obj_add_strcpy(doc, file, "name", name) ||
	    !yyjson_mut_obj_add_strcpy(doc, file, "sha256", hash) ||
	    !yyjson_mut_arr_append(files, file))
		goto out;
	strcpy(assets[*count].ref, ref);
	strcpy(assets[*count].name, name);
	(*count)++;
	*total += copied;
	rv = 0;
out:
	if (out != -1)
		close(out);
	close(in);
	return rv;
}

/* One bounded, atomic Redis read of just the referenced organisation attributes. */
static redisReply *
read_attributes(redisContext *rc, const char *org, yyjson_val *layout)
{
	static const char script[] =
	    "local t,i={},{}; for n=1,#ARGV,2 do "
	    "local a,k; if ARGV[n]=='t' then a=t; k=KEYS[1] else a=i; k=KEYS[2] end; "
	    "local v=redis.call('HGET',k,ARGV[n+1]); "
	    "if not v or #v>1023 or string.find(v,string.char(0),1,true) then "
	    "return redis.error_reply('missing or invalid snapshot attribute') end; "
	    "a[#a+1]=ARGV[n+1]; a[#a+1]=v; end; return {t,i}";
	const char *argv[405] = { "EVAL", script, "2" };
	char metadata[128], images[128];
	yyjson_val *imp;
	const char *type;
	size_t i, max;
	int argc = 5;

	if (rc == NULL)
		return NULL;
	snprintf(metadata, sizeof(metadata), "%s:metadata", org);
	snprintf(images, sizeof(images), "%s:images", org);
	argv[3] = metadata;
	argv[4] = images;
	yyjson_arr_foreach(yyjson_obj_get(layout, "imprints"), i, max, imp) {
		type = yyjson_get_str(yyjson_obj_get(imp, "type"));
		if (strcmp(type, "pim_text") != 0 && strcmp(type, "pim_image") != 0)
			continue;
		if (argc + 2 > (int)(sizeof(argv) / sizeof(argv[0])))
			return NULL;
		argv[argc++] = strcmp(type, "pim_text") == 0 ? "t" : "i";
		argv[argc++] = yyjson_get_str(yyjson_obj_get(imp, "ref"));
	}
	return argc == 5 ? NULL : redisCommandArgv(rc, argc, argv, NULL);
}

static const char *
attribute(redisReply *hash, const char *ref)
{
	size_t i;

	if (hash == NULL || hash->type != REDIS_REPLY_ARRAY || ref == NULL)
		return NULL;
	for (i = 0; i + 1 < hash->elements; i += 2)
		if (hash->element[i]->type == REDIS_REPLY_STRING &&
		    hash->element[i + 1]->type == REDIS_REPLY_STRING &&
		    strcmp(hash->element[i]->str, ref) == 0)
			return hash->element[i + 1]->str;
	return NULL;
}

char *
snapshot_create(const struct conf *cf, redisContext *rc, const char *org,
    int revision, yyjson_val *layout, const char *dir, char *err, size_t errsz)
{
	struct asset assets[MAX_ASSETS];
	yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);
	yyjson_mut_val *root, *frozen, *imps, *imp, *files;
	redisReply *pim = NULL, *text = NULL, *images = NULL;
	const char *type, *ref, *value, *font, *prefix;
	char name[32], manifest[1200], *result = NULL;
	size_t i, max, total = 0;
	int count = 0, created = 0, fd, parent, complete = 0;

	if (doc == NULL)
		goto out;
	root = yyjson_mut_obj(doc);
	frozen = yyjson_val_mut_copy(doc, layout);
	files = yyjson_mut_arr(doc);
	if (root == NULL || frozen == NULL || files == NULL || mkdir(dir, 0750) == -1)
		goto out;
	created = 1;
	yyjson_mut_doc_set_root(doc, root);
	if (!yyjson_mut_obj_add_int(doc, root, "version", 1) ||
	    !yyjson_mut_obj_add_int(doc, root, "revision", revision) ||
	    !yyjson_mut_obj_add_strcpy(doc, root, "org_code", org) ||
	    !yyjson_mut_obj_add_val(doc, root, "layout", frozen) ||
	    !yyjson_mut_obj_add_val(doc, root, "files", files) ||
	    !yyjson_mut_obj_add_strcpy(doc, root, "date_format", conf_get(cf, "date_format", "%d-%m-%Y")))
		goto out;
	font = conf_get(cf, "default_font", "");
	name[0] = '\0';
	if (*font && freeze_asset(cf, font, dir, assets, &count, &total, doc, files, name) == -1)
		goto out;
	if (!yyjson_mut_obj_add_strcpy(doc, root, "default_font", name))
		goto out;
	pim = read_attributes(rc, org, layout);
	if (pim != NULL && pim->type == REDIS_REPLY_ARRAY && pim->elements == 2) {
		text = pim->element[0];
		images = pim->element[1];
	}
	imps = yyjson_mut_obj_get(frozen, "imprints");
	yyjson_mut_arr_foreach(imps, i, max, imp) {
		type = yyjson_mut_get_str(yyjson_mut_obj_get(imp, "type"));
		ref = yyjson_mut_get_str(yyjson_mut_obj_get(imp, "ref"));
		if (strcmp(type, "pim_text") == 0) {
			value = attribute(text, ref);
			prefix = yyjson_mut_get_str(yyjson_mut_obj_get(imp, "prefix"));
			if (value == NULL || strlen(value) + (prefix ? strlen(prefix) : 0) > 1023 || !yyjson_mut_obj_put(imp, yyjson_mut_str(doc, "type"), yyjson_mut_str(doc, "resolved_text")) ||
			    !yyjson_mut_obj_put(imp, yyjson_mut_str(doc, "value"), yyjson_mut_strcpy(doc, value)))
				goto out;
		} else if (strcmp(type, "pim_image") == 0) {
			value = attribute(images, ref);
			if (value == NULL || freeze_asset(cf, value, dir, assets, &count, &total, doc, files, name) == -1 ||
			    !yyjson_mut_obj_put(imp, yyjson_mut_str(doc, "type"), yyjson_mut_str(doc, "frozen_image")) ||
			    !yyjson_mut_obj_put(imp, yyjson_mut_str(doc, "ref"), yyjson_mut_strcpy(doc, name)))
				goto out;
		}
		if (strcmp(type, "pim_text") == 0 || strcmp(type, "date") == 0 || strcmp(type, "serial") == 0) {
			font = yyjson_mut_get_str(yyjson_mut_obj_get(imp, "font"));
			if (font == NULL || !*font)
				font = conf_get(cf, "default_font", "");
			name[0] = '\0';
			if ((*font && freeze_asset(cf, font, dir, assets, &count, &total, doc, files, name) == -1) ||
			    !yyjson_mut_obj_put(imp, yyjson_mut_str(doc, "font"), yyjson_mut_strcpy(doc, name)))
				goto out;
		}
	}
	/* Keep every revision's resolved metadata, even after the DB points at a correction. */
	result = yyjson_mut_write(doc, 0, NULL);
	snprintf(manifest, sizeof(manifest), "%s/manifest.json", dir);
	if (result == NULL || write_file(manifest, result, strlen(result), 0440) == -1 ||
	    (fd = open(manifest, O_RDONLY)) == -1)
		goto out;
	if (fchmod(fd, 0440) == -1 || fsync(fd) == -1) {
		close(fd);
		goto out;
	}
	close(fd);
	if (chmod(dir, 0550) == -1 || (fd = open(dir, O_RDONLY | O_DIRECTORY)) == -1)
		goto out;
	if (fsync(fd) == -1) {
		close(fd);
		goto out;
	}
	parent = openat(fd, "..", O_RDONLY | O_DIRECTORY);
	close(fd);
	if (parent == -1)
		goto out;
	if (fsync(parent) == -1) {
		close(parent);
		goto out;
	}
	close(parent);
	complete = 1;
out:
	if (!complete) {
		free(result);
		result = NULL;
		if (created)
			snapshot_remove(dir);
		snprintf(err, errsz, "could not freeze submit inputs (missing, unsafe, changing, text over 1023 bytes or assets over 16 MB)");
	}
	if (pim != NULL)
		freeReplyObject(pim);
	yyjson_mut_doc_free(doc);
	return result;
}

void
snapshot_remove(const char *dir)
{
	DIR *d;
	struct dirent *entry;

	if (dir == NULL || !*dir || chmod(dir, 0750) == -1 || (d = opendir(dir)) == NULL)
		return;
	while ((entry = readdir(d)) != NULL)
		if ((strncmp(entry->d_name, "asset-", 6) == 0 && is_safe_name(entry->d_name)) ||
		    strcmp(entry->d_name, "manifest.json") == 0)
			unlinkat(dirfd(d), entry->d_name, 0);
	closedir(d);
	rmdir(dir);
}

int
snapshot_verify(yyjson_val *root, const char *dir, char *err, size_t errsz)
{
	yyjson_val *files = yyjson_obj_get(root, "files"), *file;
	const char *name, *expected;
	char path[1200], hash[65];
	size_t i, max;

	if (yyjson_get_sint(yyjson_obj_get(root, "version")) != 1 || !yyjson_is_arr(files) ||
	    yyjson_arr_size(files) > MAX_ASSETS)
		goto fail;
	yyjson_arr_foreach(files, i, max, file) {
		name = yyjson_get_str(yyjson_obj_get(file, "name"));
		expected = yyjson_get_str(yyjson_obj_get(file, "sha256"));
		if (!is_safe_name(name) || expected == NULL)
			goto fail;
		snprintf(path, sizeof(path), "%s/%s", dir, name);
		if (sha256_file(path, hash) == -1 || strcmp(hash, expected) != 0)
			goto fail;
	}
	return 0;
fail:
	snprintf(err, errsz, "frozen revision inputs missing or damaged; live PIM/DAM fallback is forbidden");
	return -1;
}
