/*
 * c8-tailscale-tile: keeps the Tailscale live tile fresh while the app
 * isn't open. Start runs it (tailscale.widget's Provider=) when the tile
 * is pinned and at login; it needs no Wayland. It asks tailscale every
 * half minute while Start shows, every five while it doesn't, and quits
 * when told the tile restarts or when the shell has been gone a minute.
 */
#include <gio/gio.h>
#include <glib-unix.h>
#include <signal.h>
#include <locale.h>
#include <stdio.h>
#include <string.h>
#include "stealth.h"
#include "tiles.h"
#include "tailscale.h"

#define SHOWN_S 30
#define HIDDEN_S 300

static GMainLoop *loop;
static const char *tile_id;

static void changed(void *data) {
	ts_tile_update(tile_id);
}

static void set_visible(bool visible) {
	ts_poll(visible ? SHOWN_S : HIDDEN_S);
	if (visible) {
		ts_refresh();
	}
}

static void shell_here(void *data) {
	/* A fresh shell may have lost what we sent */
	ts_tile_forget();
	ts_tile_update(tile_id);
}

static void start_visible(bool visible, void *data) {
	set_visible(visible);
}

static void leave(void *data) {
	g_main_loop_quit(loop);
}

static struct c8_tile_provider provider = {
	.quit = leave,
	.quit_unpinned = true,
	.shell = shell_here,
	.visible = start_visible,
};

int main(int argc, char **argv) {
	setlocale(LC_ALL, "");
	if (argc != 2) {
		fprintf(stderr, "Usage: c8-tailscale-tile TILE-ID\n");
		return 2;
	}
	tile_id = argv[1];
	loop = g_main_loop_new(NULL, FALSE);
	provider.tile_id = tile_id;
	c8_tile_provider_watch(&provider, NULL);
	ts_on_change(changed, NULL);
	/* Stealth mode on or off: the names on the tile change */
	c8_stealth_watch(changed, NULL);
	ts_poll(SHOWN_S);
	ts_refresh();
	g_main_loop_run(loop);
	return 0;
}
