/*
 * Finding the games installed: Steam's libraries (its manifests name each
 * game), Lutris (`lutris -l -j`) and any desktop entry in the Game
 * category (Heroic, itch, native games, Steam's own shortcuts). Steam and
 * Lutris keep pictures of their own, which make a tile without asking
 * SteamGridDB.
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gio/gio.h>
#include <gio/gdesktopappinfo.h>
#include "json.h"
#include "tiles.h"

static GPtrArray *games;
static int scan_serial;

const char *tm_source_name(enum tm_source s) {
	switch (s) {
	case TM_STEAM: return "Steam";
	case TM_LUTRIS: return "Lutris";
	default: return "Installed";
	}
}

static void game_free(gpointer p) {
	struct tm_game *g = p;
	g_free(g->name);
	g_free(g->exec);
	g_free(g->steam_appid);
	g_free(g->icon);
	g_free(g->wide);
	g_free(g->tall);
	g_free(g);
}

static struct tm_game *find_name(const char *name) {
	for (guint i = 0; i < games->len; i++) {
		struct tm_game *g = games->pdata[i];
		if (g_ascii_strcasecmp(g->name, name) == 0) {
			return g;
		}
	}
	return NULL;
}

static struct tm_game *find_appid(const char *appid) {
	for (guint i = 0; i < games->len; i++) {
		struct tm_game *g = games->pdata[i];
		if (g_strcmp0(g->steam_appid, appid) == 0) {
			return g;
		}
	}
	return NULL;
}

static char *existing(char *path) {
	if (path && g_file_test(path, G_FILE_TEST_IS_REGULAR)) {
		return path;
	}
	g_free(path);
	return NULL;
}

/* Steam */

/* The value after "key" in Valve's KeyValues text, from p on; NULL if
 * there's none. *end is set past it, for the next. */
static char *vdf_value(const char *p, const char *key, const char **end) {
	char *quoted = g_strdup_printf("\"%s\"", key);
	const char *at = p;
	char *value = NULL;
	while ((at = strcasestr(at, quoted))) {
		const char *q = at + strlen(quoted);
		while (*q == ' ' || *q == '\t') {
			q++;
		}
		if (*q != '"') {
			at = q;
			continue; // a section, not a value
		}
		const char *v = q + 1;
		GString *s = g_string_new(NULL);
		for (; *v && *v != '"'; v++) {
			if (*v == '\\' && v[1]) {
				v++;
			}
			g_string_append_c(s, *v);
		}
		value = g_string_free(s, FALSE);
		if (end) {
			*end = *v ? v + 1 : v;
		}
		break;
	}
	g_free(quoted);
	return value;
}

static bool steam_tool(const char *name, const char *appid) {
	static const char *const tools[] = { "Proton", "Steam Linux Runtime",
		"Steamworks Common", "Steam Runtime", "SteamVR" };
	for (size_t i = 0; i < G_N_ELEMENTS(tools); i++) {
		if (g_str_has_prefix(name, tools[i])) {
			return true;
		}
	}
	return strcmp(appid, "228980") == 0;
}

/* Steam's own pictures: the header is 460x215, as a wide tile is */
static void steam_art(struct tm_game *g, const char *root) {
	char *cache = g_build_filename(root, "appcache", "librarycache", NULL);
	char *name = g_strdup_printf("%s_header.jpg", g->steam_appid);
	g->wide = existing(g_build_filename(cache, name, NULL));
	g_free(name);
	if (g->wide == NULL) {
		g->wide = existing(g_build_filename(cache, g->steam_appid,
			"header.jpg", NULL));
	}
	name = g_strdup_printf("%s_library_600x900.jpg", g->steam_appid);
	g->tall = existing(g_build_filename(cache, name, NULL));
	g_free(name);
	if (g->tall == NULL) {
		g->tall = existing(g_build_filename(cache, g->steam_appid,
			"library_600x900.jpg", NULL));
	}
	g_free(cache);
	/* Steam's desktop shortcuts install an icon per game */
	static const char *const sizes[] = { "256x256", "128x128", "64x64",
		"48x48", "32x32" };
	for (size_t i = 0; g->icon == NULL && i < G_N_ELEMENTS(sizes); i++) {
		char *file = g_strdup_printf("steam_icon_%s.png", g->steam_appid);
		g->icon = existing(g_build_filename(g_get_user_data_dir(), "icons",
			"hicolor", sizes[i], "apps", file, NULL));
		g_free(file);
	}
}

static void steam_library(const char *root, const char *lib, bool flatpak) {
	char *apps = g_build_filename(lib, "steamapps", NULL);
	GDir *d = g_dir_open(apps, 0, NULL);
	const char *file;
	while (d && (file = g_dir_read_name(d))) {
		if (!g_str_has_prefix(file, "appmanifest_") ||
				!g_str_has_suffix(file, ".acf")) {
			continue;
		}
		char *path = g_build_filename(apps, file, NULL), *text = NULL;
		if (g_file_get_contents(path, &text, NULL, NULL)) {
			char *appid = vdf_value(text, "appid", NULL);
			char *name = vdf_value(text, "name", NULL);
			/* A number, as Steam's are: it goes into the tile's command,
			 * and with Flatpak's Steam a game can write these files */
			if (appid && appid[0] &&
					strspn(appid, "0123456789") == strlen(appid) && name &&
					!steam_tool(name, appid) &&
					!find_appid(appid)) {
				struct tm_game *g = g_new0(struct tm_game, 1);
				g->name = g_strdup(name);
				g->source = TM_STEAM;
				g->steam_appid = g_strdup(appid);
				g->exec = g_strdup_printf("%s steam://rungameid/%s",
					flatpak ? "flatpak run com.valvesoftware.Steam" : "steam",
					appid);
				steam_art(g, root);
				g_ptr_array_add(games, g);
			}
			g_free(appid);
			g_free(name);
		}
		g_free(text);
		g_free(path);
	}
	if (d) {
		g_dir_close(d);
	}
	g_free(apps);
}

static void scan_steam(void) {
	const char *home = g_get_home_dir();
	struct { char *root; bool flatpak; } roots[] = {
		{ g_build_filename(g_get_user_data_dir(), "Steam", NULL), false },
		{ g_build_filename(home, ".steam", "steam", NULL), false },
		{ g_build_filename(home, ".var", "app", "com.valvesoftware.Steam",
			".local", "share", "Steam", NULL), true },
		{ g_build_filename(home, ".var", "app", "com.valvesoftware.Steam",
			"data", "Steam", NULL), true },
	};
	GHashTable *seen = g_hash_table_new_full(g_str_hash, g_str_equal, g_free,
		NULL);
	for (size_t i = 0; i < G_N_ELEMENTS(roots); i++) {
		char *real = realpath(roots[i].root, NULL);
		if (real && !g_hash_table_contains(seen, real)) {
			g_hash_table_add(seen, g_strdup(real));
			char *vdf = g_build_filename(real, "steamapps",
				"libraryfolders.vdf", NULL), *text = NULL;
			steam_library(real, real, roots[i].flatpak);
			if (g_file_get_contents(vdf, &text, NULL, NULL)) {
				const char *p = text;
				char *lib;
				while ((lib = vdf_value(p, "path", &p))) {
					char *rl = realpath(lib, NULL);
					if (rl && strcmp(rl, real) != 0) {
						steam_library(real, rl, roots[i].flatpak);
					}
					free(rl);
					g_free(lib);
				}
			}
			g_free(text);
			g_free(vdf);
		}
		free(real);
		g_free(roots[i].root);
	}
	g_hash_table_unref(seen);
}

/* Desktop entries */

/* The command line without %U and the like */
char *tm_strip_codes(const char *cmd) {
	GString *s = g_string_new(NULL);
	char **argv = NULL;
	if (!g_shell_parse_argv(cmd, NULL, &argv, NULL)) {
		g_string_free(s, TRUE);
		return g_strdup(cmd);
	}
	for (int i = 0; argv[i]; i++) {
		if (argv[i][0] == '%' && argv[i][1] && argv[i][2] == '\0') {
			continue;
		}
		char *q = g_shell_quote(argv[i]);
		/* Plain words stay plain, for reading in the editor */
		bool plain = argv[i][0] && strpbrk(argv[i], " \t'\"\\$`;&|<>()*?") ==
			NULL;
		if (s->len) {
			g_string_append_c(s, ' ');
		}
		g_string_append(s, plain ? argv[i] : q);
		g_free(q);
	}
	g_strfreev(argv);
	return g_string_free(s, FALSE);
}

static void scan_desktop(void) {
	static const char *const launchers[] = { "steam.desktop",
		"com.valvesoftware.Steam.desktop", "net.lutris.Lutris.desktop",
		"lutris.desktop", "com.heroicgameslauncher.hgl.desktop",
		"heroic.desktop", "io.itch.itch.desktop", "itch.desktop" };
	GList *all = g_app_info_get_all();
	for (GList *l = all; l; l = l->next) {
		GDesktopAppInfo *info = l->data;
		const char *cats = g_desktop_app_info_get_categories(info);
		const char *id = g_app_info_get_id(G_APP_INFO(info));
		if (cats == NULL || strstr(cats, "Game") == NULL ||
				!g_app_info_should_show(G_APP_INFO(info))) {
			continue;
		}
		bool launcher = false;
		for (size_t i = 0; id && i < G_N_ELEMENTS(launchers); i++) {
			launcher |= strcmp(id, launchers[i]) == 0;
		}
		const char *name = g_app_info_get_name(G_APP_INFO(info));
		const char *cmd = g_app_info_get_commandline(G_APP_INFO(info));
		if (launcher || name == NULL || cmd == NULL || find_name(name)) {
			continue;
		}
		const char *rungame = strstr(cmd, "steam://rungameid/");
		if (rungame) {
			char *appid = g_strndup(rungame + 18, strspn(rungame + 18,
				"0123456789"));
			bool known = find_appid(appid) != NULL;
			g_free(appid);
			if (known) {
				continue;
			}
		}
		struct tm_game *g = g_new0(struct tm_game, 1);
		g->name = g_strdup(name);
		g->exec = tm_strip_codes(cmd);
		g->source = TM_DESKTOP;
		if (rungame) {
			g->steam_appid = g_strndup(rungame + 18, strspn(rungame + 18,
				"0123456789"));
			g->source = TM_STEAM;
		}
		GIcon *icon = g_app_info_get_icon(G_APP_INFO(info));
		if (G_IS_THEMED_ICON(icon)) {
			const char *const *names = g_themed_icon_get_names(
				G_THEMED_ICON(icon));
			g->icon = g_strdup(names && names[0] ? names[0] : NULL);
		} else if (G_IS_FILE_ICON(icon)) {
			g->icon = g_file_get_path(g_file_icon_get_file(G_FILE_ICON(icon)));
		}
		g_ptr_array_add(games, g);
	}
	g_list_free_full(all, g_object_unref);
}

/* Lutris */

static int by_name(gconstpointer a, gconstpointer b) {
	const struct tm_game *ga = *(struct tm_game **)a,
		*gb = *(struct tm_game **)b;
	return g_utf8_collate(ga->name, gb->name);
}

struct scan {
	tm_games_fn fn;
	void *data;
	int serial;
};

static void finish(struct scan *s) {
	if (s->serial == scan_serial) {
		/* Last, so Steam's and Lutris' own entries win over shortcuts */
		scan_desktop();
		g_ptr_array_sort(games, by_name);
		s->fn(games, s->data);
	}
	g_free(s);
}

static void lutris_done(GObject *src, GAsyncResult *res, gpointer data) {
	struct scan *s = data;
	char *out = NULL;
	if (g_subprocess_communicate_utf8_finish(G_SUBPROCESS(src), res, &out,
			NULL, NULL) && out && s->serial == scan_serial) {
		/* It may say other things before the list */
		const char *start = strchr(out, '[');
		struct json *list = start ? json_parse(start) : NULL;
		for (int i = 0; i < json_length(list); i++) {
			struct json *j = json_at(list, i);
			const char *name = json_str(json_get(j, "name"), NULL);
			const char *slug = json_str(json_get(j, "slug"), NULL);
			int id = (int)json_num(json_get(j, "id"), 0);
			if (name == NULL || id <= 0 || find_name(name)) {
				continue;
			}
			struct tm_game *g = g_new0(struct tm_game, 1);
			g->name = g_strdup(name);
			g->source = TM_LUTRIS;
			g->exec = g_strdup_printf("lutris lutris:rungameid/%d", id);
			if (slug) {
				char *file = g_strdup_printf("lutris_%s.png", slug);
				g->icon = existing(g_build_filename(g_get_user_data_dir(),
					"icons", "hicolor", "128x128", "apps", file, NULL));
				g_free(file);
				file = g_strdup_printf("%s.jpg", slug);
				g->wide = existing(g_build_filename(g_get_user_data_dir(),
					"lutris", "banners", file, NULL));
				g_free(file);
			}
			const char *cover = json_str(json_get(j, "coverPath"), NULL);
			g->tall = cover ? existing(g_strdup(cover)) : NULL;
			g_ptr_array_add(games, g);
		}
		json_free(list);
	}
	g_free(out);
	g_object_unref(src);
	finish(s);
}

void tm_games_scan(tm_games_fn fn, void *data) {
	if (games == NULL) {
		games = g_ptr_array_new_with_free_func(game_free);
	}
	g_ptr_array_set_size(games, 0);
	scan_serial++;
	scan_steam();
	struct scan *s = g_new0(struct scan, 1);
	s->fn = fn;
	s->data = data;
	s->serial = scan_serial;
	char *lutris = g_find_program_in_path("lutris");
	GSubprocess *proc = lutris ? g_subprocess_new(
		G_SUBPROCESS_FLAGS_STDOUT_PIPE | G_SUBPROCESS_FLAGS_STDERR_SILENCE,
		NULL, lutris, "-l", "-j", NULL) : NULL;
	g_free(lutris);
	if (proc) {
		g_subprocess_communicate_utf8_async(proc, NULL, NULL, lutris_done, s);
	} else {
		finish(s);
	}
}
