/* What c8-accounts and c8-sync both need for talking through curl: one
 * copy, so the two can't come to disagree on where plain http may go. */
#pragma once

#include <glib.h>
#include <stdbool.h>
#include <string.h>

/* http is fine to this machine itself (a site being tried out: nothing
 * leaves it), and anywhere when testing against a mock (as
 * C8_NEWS_ALLOW_FILE is for News). Only https otherwise. */
static inline bool plain_http_ok(const char *url) {
	static const char *const here[] = { "http://127.0.0.1", "http://localhost",
		"http://[::1]" };
	if (g_getenv("C8_ACCOUNTS_ALLOW_HTTP")) {
		return true;
	}
	for (int i = 0; i < 3; i++) {
		size_t n = strlen(here[i]);
		if (strncmp(url, here[i], n) == 0 &&
				(url[n] == '\0' || url[n] == ':' || url[n] == '/')) {
			return true;
		}
	}
	return false;
}

/* One `key = "value"` line of a curl config (--config -), quoted */
static inline void cfg(GString *conf, const char *key, const char *value) {
	g_string_append_printf(conf, "%s = \"", key);
	for (const char *p = value; *p; p++) {
		switch (*p) {
		case '\\': g_string_append(conf, "\\\\"); break;
		case '"': g_string_append(conf, "\\\""); break;
		case '\n': g_string_append(conf, "\\n"); break;
		case '\r': g_string_append(conf, "\\r"); break;
		case '\t': g_string_append(conf, "\\t"); break;
		default: g_string_append_c(conf, *p);
		}
	}
	g_string_append(conf, "\"\n");
}
