/*
 * logind and locking: `loginctl lock-session` (and anything else that
 * asks logind to lock us) locks the screen, and so does going to sleep,
 * before it happens: we hold a delay inhibitor until the compositor says
 * the screen is locked, so nothing shows when the lid opens again.
 */
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <gio/gio.h>
#include <gio/gunixfdlist.h>
#include "shell.h"

#define SLEEP_LOCK_WAIT_MS 3000

static struct {
	GDBusConnection *bus;
	char *session; // object path
	int inhibit_fd; // -1 when not held
	guint release_timer;
} lg = { .inhibit_fd = -1 };

static void lock_screen(void) {
	if (!shell.locked) {
		c8_shell_v1_launch(shell.proto, "@lock");
	}
}

/* The delay inhibitor: taken while awake, let go once locked for sleep */

static void release(void) {
	g_clear_handle_id(&lg.release_timer, g_source_remove);
	if (lg.inhibit_fd >= 0) {
		close(lg.inhibit_fd);
		lg.inhibit_fd = -1;
	}
}

static void inhibited(GObject *source, GAsyncResult *res, gpointer data) {
	GUnixFDList *fds = NULL;
	GError *err = NULL;
	GVariant *r = g_dbus_connection_call_with_unix_fd_list_finish(
		G_DBUS_CONNECTION(source), &fds, res, &err);
	if (r == NULL) {
		g_warning("logind: no sleep inhibitor: %s", err->message);
		g_error_free(err);
		return;
	}
	gint32 index;
	g_variant_get(r, "(h)", &index);
	int fd = g_unix_fd_list_get(fds, index, NULL);
	g_variant_unref(r);
	g_object_unref(fds);
	if (lg.inhibit_fd >= 0) {
		close(fd);
	} else {
		lg.inhibit_fd = fd;
	}
}

static void take_inhibitor(void) {
	if (lg.inhibit_fd >= 0) {
		return;
	}
	g_dbus_connection_call_with_unix_fd_list(lg.bus, "org.freedesktop.login1",
		"/org/freedesktop/login1", "org.freedesktop.login1.Manager", "Inhibit",
		g_variant_new("(ssss)", "sleep", "cont8nuum",
		"Locking the screen first", "delay"), G_VARIANT_TYPE("(h)"),
		G_DBUS_CALL_FLAGS_NONE, -1, NULL, NULL, inhibited, NULL);
}

static gboolean release_anyway(gpointer data) {
	lg.release_timer = 0;
	g_warning("logind: the screen didn't lock in time; sleeping anyway");
	release();
	return G_SOURCE_REMOVE;
}

/* The compositor locked or unlocked */
void logind_locked_changed(void) {
	if (shell.locked && lg.release_timer) {
		release();
	}
}

static void prepare_for_sleep(gboolean going) {
	if (!going) {
		take_inhibitor();
		return;
	}
	if (shell.locked || lg.inhibit_fd < 0) {
		release();
		return;
	}
	lock_screen();
	lg.release_timer = g_timeout_add(SLEEP_LOCK_WAIT_MS, release_anyway, NULL);
}

static void on_signal(GDBusConnection *bus, const char *sender,
		const char *path, const char *iface, const char *signal,
		GVariant *params, gpointer data) {
	if (strcmp(signal, "PrepareForSleep") == 0) {
		gboolean going;
		g_variant_get(params, "(b)", &going);
		prepare_for_sleep(going);
	} else if (strcmp(signal, "Lock") == 0) {
		lock_screen();
	}
}

/* Our session's object path, for its Lock signal */
static char *find_session(void) {
	const char *id = getenv("XDG_SESSION_ID");
	GVariant *r = id && id[0] ?
		g_dbus_connection_call_sync(lg.bus, "org.freedesktop.login1",
			"/org/freedesktop/login1", "org.freedesktop.login1.Manager",
			"GetSession", g_variant_new("(s)", id), G_VARIANT_TYPE("(o)"),
			G_DBUS_CALL_FLAGS_NONE, 1000, NULL, NULL) :
		g_dbus_connection_call_sync(lg.bus, "org.freedesktop.login1",
			"/org/freedesktop/login1", "org.freedesktop.login1.Manager",
			"GetSessionByPID", g_variant_new("(u)", (guint32)getpid()),
			G_VARIANT_TYPE("(o)"), G_DBUS_CALL_FLAGS_NONE, 1000, NULL, NULL);
	if (r == NULL) {
		return NULL;
	}
	char *path;
	g_variant_get(r, "(o)", &path);
	g_variant_unref(r);
	return path;
}

void logind_init(void) {
	lg.bus = g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, NULL);
	if (lg.bus == NULL) {
		return;
	}
	g_dbus_connection_signal_subscribe(lg.bus, "org.freedesktop.login1",
		"org.freedesktop.login1.Manager", "PrepareForSleep",
		"/org/freedesktop/login1", NULL, G_DBUS_SIGNAL_FLAGS_NONE, on_signal,
		NULL, NULL);
	lg.session = find_session();
	if (lg.session) {
		g_dbus_connection_signal_subscribe(lg.bus, "org.freedesktop.login1",
			"org.freedesktop.login1.Session", "Lock", lg.session, NULL,
			G_DBUS_SIGNAL_FLAGS_NONE, on_signal, NULL, NULL);
	}
	take_inhibitor();
}
