/*
 * Fetching with curl: a subprocess per request, so the app needs no HTTP
 * library and a hung server only costs its timeout. Only http and https
 * (and file, for tests, when C8_NEWS_ALLOW_FILE is set) are followed.
 */
#include <gio/gio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "news.h"

#define MAX_BYTES "25M"
#define TIMEOUT "30"

struct fetch {
	char *dest, *tmp, *hdr;
	fetch_fn fn;
	void *data;
};

static void fetch_free(struct fetch *f) {
	g_free(f->dest);
	g_free(f->tmp);
	g_free(f->hdr);
	g_free(f);
}

/* The last ETag and Last-Modified in curl's header dump */
static void read_headers(const char *path, char **etag, char **modified) {
	char *text = NULL;
	if (!g_file_get_contents(path, &text, NULL, NULL)) {
		return;
	}
	char **lines = g_strsplit(text, "\n", -1);
	for (char **l = lines; *l; l++) {
		char *line = g_strstrip(*l);
		if (g_ascii_strncasecmp(line, "etag:", 5) == 0) {
			g_free(*etag);
			*etag = g_strdup(g_strstrip(line + 5));
		} else if (g_ascii_strncasecmp(line, "last-modified:", 14) == 0) {
			g_free(*modified);
			*modified = g_strdup(g_strstrip(line + 14));
		}
	}
	g_strfreev(lines);
	g_free(text);
}

static void finished(GObject *source, GAsyncResult *res, gpointer data) {
	struct fetch *f = data;
	GSubprocess *proc = G_SUBPROCESS(source);
	char *out = NULL;
	int status = 0;
	if (g_subprocess_communicate_utf8_finish(proc, res, &out, NULL, NULL) &&
			g_subprocess_get_if_exited(proc)) {
		int code = out ? atoi(out) : 0;
		/* file:// has no HTTP status */
		status = code > 0 ? code : g_subprocess_get_exit_status(proc) == 0 ?
			200 : 0;
		if (g_subprocess_get_exit_status(proc) != 0 && code != 304) {
			status = 0;
		}
	}
	g_free(out);
	char *etag = NULL, *modified = NULL;
	if (status == 200) {
		read_headers(f->hdr, &etag, &modified);
		if (g_rename(f->tmp, f->dest) != 0) {
			status = 0;
		}
	}
	g_unlink(f->hdr);
	if (status != 200) {
		g_unlink(f->tmp);
	}
	f->fn(status, etag, modified, f->data);
	g_free(etag);
	g_free(modified);
	g_object_unref(proc);
	fetch_free(f);
}

void fetch_start(const char *url, const char *dest, const char *etag,
		const char *modified, fetch_fn fn, void *data) {
	struct fetch *f = g_new0(struct fetch, 1);
	f->dest = g_strdup(dest);
	f->tmp = g_strconcat(dest, ".part", NULL);
	f->hdr = g_strconcat(dest, ".hdr", NULL);
	f->fn = fn;
	f->data = data;
	char *dir = g_path_get_dirname(dest);
	g_mkdir_with_parents(dir, 0700);
	g_free(dir);

	const char *protos = g_getenv("C8_NEWS_ALLOW_FILE") ? "=https,http,file" :
		"=https,http";
	GPtrArray *argv = g_ptr_array_new();
	const char *fixed[] = { "curl", "-sL", "--max-redirs", "5", "--proto",
		protos, "--proto-redir", "=https,http", "--max-time", TIMEOUT,
		"--max-filesize", MAX_BYTES, "--compressed", "-A",
		"c8-news/0.1 (cont8nuum)", "-D", f->hdr, "-o", f->tmp, "-w",
		"%{http_code}", NULL };
	for (int i = 0; fixed[i]; i++) {
		g_ptr_array_add(argv, (gpointer)fixed[i]);
	}
	char *inm = etag && etag[0] ? g_strconcat("If-None-Match: ", etag, NULL) : NULL;
	char *ims = modified && modified[0] ?
		g_strconcat("If-Modified-Since: ", modified, NULL) : NULL;
	if (inm) {
		g_ptr_array_add(argv, "-H");
		g_ptr_array_add(argv, inm);
	}
	if (ims) {
		g_ptr_array_add(argv, "-H");
		g_ptr_array_add(argv, ims);
	}
	g_ptr_array_add(argv, "--");
	g_ptr_array_add(argv, (gpointer)url);
	g_ptr_array_add(argv, NULL);

	GError *err = NULL;
	GSubprocess *proc = g_subprocess_newv((const char *const *)argv->pdata,
		G_SUBPROCESS_FLAGS_STDOUT_PIPE | G_SUBPROCESS_FLAGS_STDERR_SILENCE, &err);
	g_ptr_array_free(argv, TRUE);
	g_free(inm);
	g_free(ims);
	if (proc == NULL) {
		/* No curl */
		g_error_free(err);
		fn(0, NULL, NULL, data);
		fetch_free(f);
		return;
	}
	g_subprocess_communicate_utf8_async(proc, NULL, NULL, finished, f);
}
