/*
 * The desktop session around the compositor:
 *
 * - systemd: our environment goes to the user manager and D-Bus, then
 *   cont8nuum-session.target starts, which brings up graphical-session.target
 *   (PipeWire, portals and anything else bound to it) and XDG autostart.
 *   It stops again when we quit.
 * - Idle: the screens go off and then the PC sleeps after the times in
 *   [power], unless an app (a video, say) inhibits idling. Other tools can
 *   watch idleness too, through ext-idle-notify.
 */
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>
#include <wlr/types/wlr_idle_inhibit_v1.h>
#include <wlr/types/wlr_idle_notify_v1.h>
#include <wlr/util/log.h>
#include "server.h"

/* What the user manager and D-Bus activated services need to find us
 * and our data (XDG_DATA_DIRS: a release's launcher puts /opt/cont8nuum
 * in it), how sudo -A, ssh and git ask for passwords, and where Chromium
 * keeps its keys (see set_wallet) */
#define SESSION_VARS "WAYLAND_DISPLAY DISPLAY XDG_CURRENT_DESKTOP XDG_DATA_DIRS " \
	"XDG_SESSION_TYPE XDG_SESSION_DESKTOP SUDO_ASKPASS SSH_ASKPASS " \
	"GNOME_DESKTOP_SESSION_ID XCURSOR_THEME XCURSOR_SIZE SSH_AUTH_SOCK " \
	"FREETYPE_PROPERTIES " \
	"XR_RUNTIME_JSON VR_OVERRIDE PRESSURE_VESSEL_IMPORT_OPENXR_1_RUNTIMES " \
	"PRESSURE_VESSEL_FILESYSTEMS_RW" // VR games: xrruntime.c

/* c8-askpass from $PATH, NULL if it isn't installed */
static char *find_askpass(void) {
	const char *path = getenv("PATH");
	char *copy = strdup(path ? path : "/usr/local/bin:/usr/bin");
	char *found = NULL;
	for (char *dir = strtok(copy, ":"); dir && !found; dir = strtok(NULL, ":")) {
		char *file;
		if (asprintf(&file, "%s/c8-askpass", dir) < 0) {
			break;
		}
		if (access(file, X_OK) == 0) {
			found = file;
		} else {
			free(file);
		}
	}
	free(copy);
	return found;
}

/* Our password box, unless the user picked another */
static void set_askpass(void) {
	char *askpass = find_askpass();
	if (askpass == NULL) {
		return;
	}
	setenv("SUDO_ASKPASS", askpass, false);
	setenv("SSH_ASKPASS", askpass, false);
	free(askpass);
}

/* Chromium and every Electron app pick where to keep their keys by the
 * desktop's name, and one they don't know ("cont8nuum") gets a key
 * written in their own source code. This old GNOME variable is the one
 * hint they still read after XDG_CURRENT_DESKTOP, and makes them use the
 * Secret Service: the wallet (oo7 0.6 or newer; 0.4.3 hangs them). It
 * also sends xdg-open to gio open. */
static void set_wallet(void) {
	setenv("GNOME_DESKTOP_SESSION_ID", "this-is-deprecated", false);
}

/* Without an agent ssh asks for a key's passphrase on every git command.
 * Ours (cont8nuum-ssh-agent.service) runs only when the login didn't give
 * us one already (gpg-agent, gcr, a profile script); true if it should. */
static bool set_ssh_agent(void) {
	const char *runtime = getenv("XDG_RUNTIME_DIR");
	if (getenv("SSH_AUTH_SOCK") || runtime == NULL) {
		return false;
	}
	char *sock;
	if (asprintf(&sock, "%s/cont8nuum-ssh-agent.socket", runtime) < 0) {
		return false;
	}
	setenv("SSH_AUTH_SOCK", sock, true);
	free(sock);
	return true;
}

static bool have_systemd(void) {
	return system("systemctl --user show-environment >/dev/null 2>&1") == 0;
}

void c8_session_start(struct c8_server *server) {
	setenv("XDG_SESSION_DESKTOP", "cont8nuum", true);
	if (getenv("DBUS_SESSION_BUS_ADDRESS") == NULL) {
		wlr_log(WLR_INFO, "No D-Bus session bus; start cont8nuum through "
			"dbus-run-session for notifications, portals and the like");
	}
	/* Nested in another desktop, that desktop owns the session */
	if (server->session == NULL) {
		wlr_log(WLR_INFO, "Nested: leaving the session services alone");
		return;
	}
	set_askpass();
	set_wallet();
	server->session_systemd = have_systemd();
	/* The agent needs systemd; without it, leave SSH_AUTH_SOCK unset
	 * rather than pointing at nothing */
	bool agent = server->session_systemd && set_ssh_agent();
	if (server->session_systemd) {
		/* Async: the target may take a while, we don't wait for it.
		 * The reload reruns systemd's generators, so XDG autostart
		 * follows the autostart folders as they are now: with lingering
		 * the user manager outlives logins and would remember them as
		 * they were when it started (and it needs our desktop name for
		 * OnlyShowIn). */
		c8_exec(agent
			? "dbus-update-activation-environment --systemd " SESSION_VARS
			  " && systemctl --user daemon-reload"
			  " && systemctl --user start cont8nuum-session.target"
			  " cont8nuum-ssh-agent.service"
			: "dbus-update-activation-environment --systemd " SESSION_VARS
			  " && systemctl --user daemon-reload"
			  " && systemctl --user start cont8nuum-session.target");
		wlr_log(WLR_INFO, "Starting cont8nuum-session.target");
	} else {
		c8_exec("dbus-update-activation-environment " SESSION_VARS);
		wlr_log(WLR_INFO, "No systemd user manager; session services "
			"and XDG autostart won't start");
	}
}

/* Apps started by systemd or D-Bus from now on get the new values. One
 * that is now unset leaves systemd's; D-Bus can't forget a variable. */
void c8_session_env_changed(struct c8_server *server, const char *vars) {
	if (server->session == NULL) {
		return;
	}
	char set[256] = "", unset[256] = "", copy[256];
	snprintf(copy, sizeof(copy), "%s", vars);
	for (char *n = strtok(copy, " "); n; n = strtok(NULL, " ")) {
		char *list = getenv(n) ? set : unset;
		size_t len = strlen(list);
		snprintf(list + len, sizeof(set) - len, " %s", n);
	}
	char cmd[640] = "true";
	size_t len = strlen(cmd);
	if (set[0]) {
		len += snprintf(cmd + len, sizeof(cmd) - len,
			"; dbus-update-activation-environment%s%s",
			server->session_systemd ? " --systemd" : "", set);
	}
	if (unset[0] && server->session_systemd && len < sizeof(cmd)) {
		snprintf(cmd + len, sizeof(cmd) - len,
			"; systemctl --user unset-environment%s", unset);
	}
	c8_exec(cmd);
}

void c8_session_stop(struct c8_server *server) {
	if (!server->session_systemd) {
		return;
	}
	/* Wait, so the services leave while they can still say goodbye to us;
	 * then forget us, so nothing started later talks to a dead display */
	int status = system("timeout 10 systemctl --user stop "
		"cont8nuum-session.target graphical-session.target; "
		"systemctl --user unset-environment " SESSION_VARS);
	if (status != 0) {
		wlr_log(WLR_ERROR, "Stopping the session services failed");
	}
}

/* Idle */

#define LOCKED_SCREEN_OFF 1 // minutes

static bool inhibited(struct c8_server *server) {
	return server->idle_inhibitors > 0;
}

static void screens_set(struct c8_server *server, bool on) {
	if (server->screens_off == !on) {
		return;
	}
	server->screens_off = !on;
	struct c8_output *output;
	wl_list_for_each(output, &server->outputs, link) {
		if (on ? !output->idle_off : !output->wlr_output->enabled) {
			continue;
		}
		struct wlr_output_state state;
		wlr_output_state_init(&state);
		wlr_output_state_set_enabled(&state, on);
		if (wlr_output_commit_state(output->wlr_output, &state)) {
			output->idle_off = !on;
		} else {
			wlr_log(WLR_ERROR, "Couldn't turn %s %s",
				output->wlr_output->name, on ? "on" : "off");
		}
		wlr_output_state_finish(&state);
	}
	if (on) {
		c8_schedule_tick(server);
	}
}

static void arm(struct wl_event_source *timer, int minutes) {
	if (timer) {
		wl_event_source_timer_update(timer, minutes > 0 ? minutes * 60000 : 0);
	}
}

static int screen_off_timeout(void *data) {
	struct c8_server *server = data;
	if (inhibited(server)) {
		c8_idle_configure(server);
		return 0;
	}
	wlr_log(WLR_DEBUG, "Idle: turning the screens off");
	screens_set(server, false);
	if (server->config.lock_when_off && server->session) {
		c8_lock(server);
	}
	return 0;
}

static int sleep_timeout(void *data) {
	struct c8_server *server = data;
	if (inhibited(server)) {
		c8_idle_configure(server);
		return 0;
	}
	wlr_log(WLR_INFO, "Idle: going to sleep");
	if (server->config.lock_when_off) {
		c8_lock(server);
	}
	c8_exec(server->config.sleep_cmd);
	/* Waking up is activity, which starts the timers again */
	return 0;
}

void c8_idle_activity(struct c8_server *server) {
	if (server->idle_notifier) {
		wlr_idle_notifier_v1_notify_activity(server->idle_notifier, server->seat);
	}
	screens_set(server, true);
	c8_idle_configure(server);
}

void c8_idle_configure(struct c8_server *server) {
	bool nested = server->session == NULL;
	int off = server->config.screen_off_after;
	/* Nobody's looking at a locked screen: dark after a minute */
	if (c8_locked(server)) {
		off = LOCKED_SCREEN_OFF;
	}
	arm(server->screen_off_timer, nested ? 0 : off);
	arm(server->sleep_timer, nested ? 0 : server->config.sleep_after);
}

struct inhibitor {
	struct c8_server *server;
	struct wl_listener destroy;
};

static void inhibitor_destroy(struct wl_listener *listener, void *data) {
	struct inhibitor *inhibitor = wl_container_of(listener, inhibitor, destroy);
	struct c8_server *server = inhibitor->server;
	wl_list_remove(&inhibitor->destroy.link);
	free(inhibitor);
	server->idle_inhibitors--;
	if (!server->terminating) {
		wlr_idle_notifier_v1_set_inhibited(server->idle_notifier,
			server->idle_inhibitors > 0);
	}
}

static void new_inhibitor(struct wl_listener *listener, void *data) {
	struct c8_server *server =
		wl_container_of(listener, server, new_idle_inhibitor);
	struct wlr_idle_inhibitor_v1 *wlr = data;
	struct inhibitor *inhibitor = calloc(1, sizeof(*inhibitor));
	inhibitor->server = server;
	c8_listen(&inhibitor->destroy, &wlr->events.destroy, inhibitor_destroy);
	server->idle_inhibitors++;
	wlr_idle_notifier_v1_set_inhibited(server->idle_notifier, true);
}

void c8_idle_init(struct c8_server *server) {
	server->idle_notifier = wlr_idle_notifier_v1_create(server->display);
	server->idle_inhibit = wlr_idle_inhibit_v1_create(server->display);
	c8_listen(&server->new_idle_inhibitor, &server->idle_inhibit->events.new_inhibitor,
		new_inhibitor);
	server->screen_off_timer =
		wl_event_loop_add_timer(server->loop, screen_off_timeout, server);
	server->sleep_timer =
		wl_event_loop_add_timer(server->loop, sleep_timeout, server);
	c8_idle_configure(server);
}

void c8_idle_finish(struct c8_server *server) {
	wl_list_remove(&server->new_idle_inhibitor.link);
	wl_event_source_remove(server->screen_off_timer);
	wl_event_source_remove(server->sleep_timer);
	server->screen_off_timer = server->sleep_timer = NULL;
}
