#include <gio/gio.h>
#include <glib/gstdio.h>
#include <stdlib.h>
#include <string.h>
#include "http.h"

#define TIMEOUT "30"
#define MAX_BYTES "20M"

struct call {
	c8_http_fn fn;
	void *data;
	char *dest; // downloading: the file, written as dest.part first
};

/* One line of curl's config: key = "value", quoted its way */
static void cfg(GString *s, const char *key, const char *value) {
	g_string_append_printf(s, "%s = \"", key);
	for (const char *p = value; *p; p++) {
		if (*p == '\n') {
			g_string_append(s, "\\n");
			continue;
		}
		if (*p == '\t') {
			g_string_append(s, "\\t");
			continue;
		}
		if (*p == '"' || *p == '\\') {
			g_string_append_c(s, '\\');
		}
		g_string_append_c(s, *p);
	}
	g_string_append(s, "\"\n");
}

static void done(GObject *source, GAsyncResult *res, gpointer data) {
	struct call *c = data;
	GBytes *out = NULL;
	int status = 0;
	char *body = NULL;
	if (g_subprocess_communicate_finish(G_SUBPROCESS(source), res, &out, NULL,
			NULL) && out) {
		gsize len;
		const char *bytes = g_bytes_get_data(out, &len);
		body = g_strndup(bytes, len);
		/* -w puts the status on a line of its own after the body */
		char *last = strrchr(body, '\n');
		status = atoi(last ? last + 1 : body);
		if (last) {
			*last = '\0';
		} else {
			body[0] = '\0';
		}
	}
	if (out) {
		g_bytes_unref(out);
	}
	g_object_unref(source);
	if (c->dest) {
		char *part = g_strconcat(c->dest, ".part", NULL);
		if (status != 200 || g_rename(part, c->dest) != 0) {
			g_unlink(part);
			status = status == 200 ? 0 : status;
		}
		g_free(part);
		g_clear_pointer(&body, g_free);
	}
	c->fn(status, body, c->data);
	g_free(body);
	g_free(c->dest);
	g_free(c);
}

void c8_http(const struct c8_http *request, c8_http_fn fn, void *data) {
	const char *method = request->method ? request->method : "GET";
	const char *url = request->url, *body = request->body;
	const char *token = request->token, *dest = request->dest;
	struct call *c = g_new0(struct call, 1);
	c->fn = fn;
	c->data = data;
	GString *conf = g_string_new(NULL);
	cfg(conf, "url", url);
	if (dest) {
		c->dest = g_strdup(dest);
		char *dir = g_path_get_dirname(dest);
		g_mkdir_with_parents(dir, 0700);
		g_free(dir);
		char *part = g_strconcat(dest, ".part", NULL);
		cfg(conf, "output", part);
		g_free(part);
	}
	if (request->accept) {
		char *accept = g_strconcat("Accept: ", request->accept, NULL);
		cfg(conf, "header", accept);
		g_free(accept);
	}
	if (token) {
		char *auth = g_strconcat("Authorization: Bearer ", token, NULL);
		cfg(conf, "header", auth);
		g_free(auth);
	}
	if (strcmp(method, "GET") != 0) {
		cfg(conf, "request", method);
	}
	if (request->upload) {
		char *type = g_strconcat("Content-Type: ", request->content_type ?
			request->content_type : "application/octet-stream", NULL);
		char *file = g_strconcat("@", request->upload, NULL);
		cfg(conf, "header", type);
		cfg(conf, "data-binary", file);
		g_free(type);
		g_free(file);
	} else if (body) {
		cfg(conf, "header", "Content-Type: application/json");
		cfg(conf, "data-binary", body);
	}
	const char *argv[24]; // 16 with -L, and the NULL after
	int n = 0;
	argv[n++] = "curl";
	argv[n++] = "-s";
	if (request->follow) {
		argv[n++] = "-L";
	}
	argv[n++] = "--proto";
	argv[n++] = request->allow_http ? "=https,http" : "=https";
	argv[n++] = "--max-time";
	argv[n++] = TIMEOUT;
	argv[n++] = "--max-filesize";
	argv[n++] = MAX_BYTES;
	argv[n++] = "--compressed";
	argv[n++] = "-A";
	argv[n++] = request->agent ? request->agent : "cont8nuum";
	argv[n++] = "-w";
	argv[n++] = "\n%{http_code}";
	argv[n++] = "--config";
	argv[n++] = "-";
	argv[n] = NULL;
	GError *error = NULL;
	GSubprocess *proc = g_subprocess_newv(argv, G_SUBPROCESS_FLAGS_STDIN_PIPE |
		G_SUBPROCESS_FLAGS_STDOUT_PIPE | G_SUBPROCESS_FLAGS_STDERR_SILENCE,
		&error);
	if (proc == NULL) {
		/* No curl */
		g_error_free(error);
		g_string_free(conf, TRUE);
		fn(0, NULL, data);
		g_free(c->dest);
		g_free(c);
		return;
	}
	gsize len = conf->len;
	GBytes *in = g_bytes_new_take(g_string_free(conf, FALSE), len);
	g_subprocess_communicate_async(proc, in, NULL, done, c);
	g_bytes_unref(in);
}
