/*
 * Stealth mode: what the app and the tile show of the tailnet, with the
 * names, addresses, logins and tailnets swapped for made-up ones while
 * `[stealth] on` (c8-base's stealth.h). Only for drawing: the parsed
 * status keeps the real values, which every command is given.
 *
 * What's returned is kept for the program's life (one per real value
 * and persona; the tailnet is bounded), so draw fns may use it.
 */
#include <string.h>
#include "stealth.h"
#include "tailscale.h"

#define MULLVAD_SUFFIX "mullvad.ts.net"

static GHashTable *kept; // kind, persona and real value -> shown

/* Mullvad's nodes are public, the same for everyone: they stay */
static bool is_mullvad_dns(const char *s) {
	return g_str_has_suffix(s, "." MULLVAD_SUFFIX) ||
		strcmp(s, MULLVAD_SUFFIX) == 0;
}

static char *key(char kind, const char *s) {
	return g_strdup_printf("%c%s\x1f%s\x1f%s\x1f%s", kind, c8_stealth_name(),
		c8_stealth_host(), c8_stealth_email(), s);
}

static const char *lookup(char kind, const char *s) {
	if (kept == NULL) {
		kept = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);
	}
	char *k = key(kind, s);
	const char *v = g_hash_table_lookup(kept, k);
	g_free(k);
	return v;
}

static const char *keep(char kind, const char *s, char *shown) {
	g_hash_table_insert(kept, key(kind, s), shown);
	return shown;
}

/* "laptop 2" -> "laptop-2", to sit in a DNS name */
static char *dns_label(const char *s) {
	char *l = g_ascii_strdown(s, -1);
	for (char *c = l; *c; c++) {
		if (!g_ascii_isalnum(*c) && *c != '-') {
			*c = '-';
		}
	}
	return l;
}

/* The n-th tailnet (or MagicDNS suffix) seen: its stand-in */
static guint tailnet_index(GHashTable **seen, const char *s) {
	if (*seen == NULL) {
		*seen = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, NULL);
	}
	gpointer n;
	if (!g_hash_table_lookup_extended(*seen, s, NULL, &n)) {
		n = GUINT_TO_POINTER(g_hash_table_size(*seen));
		g_hash_table_insert(*seen, g_strdup(s), n);
	}
	return GPOINTER_TO_UINT(n);
}

const char *ts_shown_self(void) {
	return c8_stealth() ? c8_stealth_host() : ts.self_name;
}

const char *ts_shown_name(const struct ts_peer *p) {
	if (!c8_stealth() || p->mullvad || p->name == NULL) {
		return p->name;
	}
	return c8_stealth_alias(C8_STEALTH_DEVICE, p->name);
}

const char *ts_shown_host(const struct ts_peer *p) {
	if (!c8_stealth() || p->mullvad || p->host == NULL) {
		return p->host;
	}
	/* Mostly the same name in another case: the same stand-in */
	if (p->name && g_ascii_strcasecmp(p->host, p->name) == 0) {
		return ts_shown_name(p);
	}
	return c8_stealth_alias(C8_STEALTH_DEVICE, p->host);
}

const char *ts_shown_suffix(const char *s) {
	if (!c8_stealth() || s == NULL || s[0] == '\0' || is_mullvad_dns(s)) {
		return s;
	}
	const char *v = lookup('s', s);
	if (v) {
		return v;
	}
	static GHashTable *seen;
	guint n = tailnet_index(&seen, s);
	return keep('s', s, n == 0 ? g_strdup("example.ts.net") :
		g_strdup_printf("example-%u.ts.net", n + 1));
}

const char *ts_shown_dns(const char *s) {
	if (!c8_stealth() || s == NULL || s[0] == '\0' || is_mullvad_dns(s)) {
		return s;
	}
	const char *v = lookup('d', s);
	if (v) {
		return v;
	}
	const char *dot = strchr(s, '.');
	char *label = dot ? g_strndup(s, dot - s) : g_strdup(s);
	char *host = ts.self_dns && strcmp(s, ts.self_dns) == 0 ?
		g_strdup(c8_stealth_host()) :
		dns_label(c8_stealth_alias(C8_STEALTH_DEVICE, label));
	char *shown = dot ? g_strdup_printf("%s.%s", host,
		ts_shown_suffix(dot + 1)) : g_strdup(host);
	g_free(label);
	g_free(host);
	return keep('d', s, shown);
}

const char *ts_shown_ip(const char *s) {
	return c8_stealth_alias(C8_STEALTH_ADDRESS, s);
}

const char *ts_shown_endpoint(const char *s) {
	if (!c8_stealth() || s == NULL || s[0] == '\0') {
		return s;
	}
	const char *v = lookup('e', s);
	if (v) {
		return v;
	}
	/* "1.2.3.4:41641", "[2001:db8::1]:41641" */
	const char *colon = strrchr(s, ':');
	char *shown;
	if (s[0] == '[' && strchr(s, ']')) {
		const char *end = strchr(s, ']');
		char *ip = g_strndup(s + 1, end - s - 1);
		shown = g_strdup_printf("[%s]%s", ts_shown_ip(ip), end + 1);
		g_free(ip);
	} else if (colon && strchr(s, ':') == colon) {
		char *ip = g_strndup(s, colon - s);
		shown = g_strdup_printf("%s%s", ts_shown_ip(ip), colon);
		g_free(ip);
	} else {
		shown = g_strdup(ts_shown_ip(s));
	}
	return keep('e', s, shown);
}

static bool tagged(const char *s) {
	return strcmp(s, "tagged-devices") == 0 ||
		strcmp(s, "Tagged Devices") == 0;
}

const char *ts_shown_owner(const char *s) {
	if (!c8_stealth() || s == NULL || tagged(s)) {
		return s;
	}
	if (g_strcmp0(s, ts.user_name) == 0 || g_strcmp0(s, ts.user_login) == 0) {
		return c8_stealth_name();
	}
	return c8_stealth_alias(C8_STEALTH_PERSON, s);
}

const char *ts_shown_login(const char *s) {
	if (!c8_stealth() || s == NULL || s[0] == '\0' || tagged(s)) {
		return s;
	}
	if (g_strcmp0(s, ts.user_login) == 0) {
		return c8_stealth_email();
	}
	const char *v = lookup('l', s);
	if (v) {
		return v;
	}
	char *who = dns_label(c8_stealth_alias(C8_STEALTH_PERSON, s));
	char *shown = g_strdup_printf("%s@example.com", who);
	g_free(who);
	return keep('l', s, shown);
}

const char *ts_shown_tailnet(const char *s) {
	if (!c8_stealth() || s == NULL || s[0] == '\0') {
		return s;
	}
	/* A personal tailnet is named after its owner's login */
	if (strchr(s, '@')) {
		return ts_shown_login(s);
	}
	const char *v = lookup('t', s);
	if (v) {
		return v;
	}
	static const char *const tlds[] = { "com", "org", "net" };
	static GHashTable *seen;
	guint n = tailnet_index(&seen, s);
	return keep('t', s, n < 3 ? g_strdup_printf("example.%s", tlds[n]) :
		g_strdup_printf("example-%u.com", n + 1));
}

static bool word_char(char c) {
	return g_ascii_isalnum(c) || c == '-' || c == '_';
}

/* Each whole word find (case as given) becomes with */
static void replace(GString *s, const char *find, const char *with) {
	size_t n = find ? strlen(find) : 0;
	if (n < 2 || with == NULL || strcmp(find, with) == 0) {
		return;
	}
	for (size_t i = 0; i + n <= s->len;) {
		if (strncmp(s->str + i, find, n) == 0 &&
				(i == 0 || !word_char(s->str[i - 1])) &&
				(i + n == s->len || !word_char(s->str[i + n]))) {
			g_string_erase(s, i, n);
			g_string_insert(s, i, with);
			i += strlen(with);
		} else {
			i++;
		}
	}
}

static bool ip_char(char c) {
	return g_ascii_isxdigit(c) || c == '.' || c == ':';
}

/* Every IPv4 or IPv6 address (with a port or not) in s, swapped */
static void replace_addresses(GString *s) {
	for (size_t i = 0; i < s->len;) {
		if (!ip_char(s->str[i]) || (i > 0 && g_ascii_isalnum(s->str[i - 1]))) {
			i++;
			continue;
		}
		size_t end = i;
		while (end < s->len && ip_char(s->str[end])) {
			end++;
		}
		/* A full stop or a colon after it isn't part of it */
		while (end > i && (s->str[end - 1] == '.' ||
				(s->str[end - 1] == ':' && (end - i < 2 ||
				s->str[end - 2] != ':')))) {
			end--;
		}
		if (end < s->len && g_ascii_isalnum(s->str[end])) {
			i = end + 1;
			continue;
		}
		char *word = g_strndup(s->str + i, end - i);
		size_t len = end - i;
		const char *with = NULL;
		if (g_hostname_is_ip_address(word)) {
			with = ts_shown_ip(word);
		} else {
			/* IPv4 with a port */
			char *colon = strchr(word, ':');
			if (colon && strchr(word, '.') && strrchr(word, ':') == colon) {
				*colon = '\0';
				if (g_hostname_is_ip_address(word)) {
					with = ts_shown_ip(word);
					len = colon - word;
				}
			}
		}
		if (with && strcmp(with, word) != 0) {
			g_string_erase(s, i, len);
			g_string_insert(s, i, with);
			i += strlen(with);
		} else {
			i = end > i ? end : i + 1;
		}
		g_free(word);
	}
}

char *ts_shown_text(const char *s) {
	if (s == NULL || !c8_stealth()) {
		return g_strdup(s);
	}
	GString *out = g_string_new(s);
	/* Whole DNS names before the labels they start with */
	for (guint i = 0; ts.peers && i < ts.peers->len; i++) {
		struct ts_peer *p = ts.peers->pdata[i];
		if (!p->mullvad) {
			replace(out, p->dns, ts_shown_dns(p->dns));
		}
	}
	replace(out, ts.self_dns, ts_shown_dns(ts.self_dns));
	replace(out, ts.magic_dns, ts_shown_suffix(ts.magic_dns));
	for (guint i = 0; ts.peers && i < ts.peers->len; i++) {
		struct ts_peer *p = ts.peers->pdata[i];
		if (!p->mullvad) {
			replace(out, p->name, ts_shown_name(p));
			replace(out, p->host, ts_shown_host(p));
		}
	}
	replace(out, ts.self_name, ts_shown_self());
	replace(out, ts.hostname, ts_shown_self());
	replace(out, ts.user_login, ts_shown_login(ts.user_login));
	replace(out, ts.tailnet, ts_shown_tailnet(ts.tailnet));
	replace(out, ts.user_name, ts_shown_owner(ts.user_name));
	replace_addresses(out);
	char *s2 = c8_stealth_text(out->str); // the login, home folder, PC name
	g_string_free(out, TRUE);
	return s2;
}
