/*
 * A toast when a drive is plugged in (a USB stick, a card, a phone):
 * its name, and Open to mount it and show it in the file manager.
 * Nothing is mounted until asked.
 *
 * The drives come from GIO's volume monitor (gvfs's udisks2 one, when
 * it's installed), as Files' places do. It only tells of what arrives
 * after we start, so the drives there at login say nothing.
 */
#define _GNU_SOURCE
#include <gio/gio.h>
#include "shell.h"

static GVolumeMonitor *monitor;

static void show(GVolume *volume) {
	GMount *mount = g_volume_get_mount(volume);
	GFile *root = mount ? g_mount_get_root(mount) :
		g_volume_get_activation_root(volume);
	if (root) {
		char *uri = g_file_get_uri(root);
		char *quoted = g_shell_quote(uri);
		char *cmd = g_strdup_printf("xdg-open %s", quoted);
		c8_shell_v1_launch(shell.proto, cmd);
		g_free(cmd);
		g_free(quoted);
		g_free(uri);
		g_object_unref(root);
	}
	g_clear_object(&mount);
}

static void mounted(GObject *source, GAsyncResult *res, gpointer data) {
	GVolume *volume = G_VOLUME(source);
	GError *error = NULL;
	if (g_volume_mount_finish(volume, res, &error)) {
		show(volume);
	} else {
		/* Pulled out again, or locked: nothing a toast could add that
		 * opening it in Files won't say better */
		g_warning("Drive: %s", error->message);
		g_error_free(error);
	}
	g_object_unref(volume);
}

static void answered(bool yes, void *data) {
	GVolume *volume = data;
	if (!yes) {
		g_object_unref(volume);
		return;
	}
	GMount *mount = g_volume_get_mount(volume);
	if (mount) {
		g_object_unref(mount);
		show(volume);
		g_object_unref(volume);
	} else if (g_volume_can_mount(volume)) {
		g_volume_mount(volume, G_MOUNT_MOUNT_NONE, NULL, NULL, mounted,
			volume);
	} else {
		g_object_unref(volume);
	}
}

static void volume_added(GVolumeMonitor *m, GVolume *volume, gpointer data) {
	GDrive *drive = g_volume_get_drive(volume);
	bool removable = drive ? g_drive_is_removable(drive) ||
		g_drive_is_media_removable(drive) || g_drive_can_eject(drive) :
		g_volume_can_eject(volume);
	g_clear_object(&drive);
	/* Not the PC's own disks, nor what the system says to leave alone
	 * (recovery and boot partitions) */
	if (!removable || !g_volume_should_automount(volume)) {
		return;
	}
	char *name = g_volume_get_name(volume);
	notify_ask(name && name[0] ? c8_stealth_show(name) : "Removable drive",
		"This drive was just plugged in.", "drive-removable-media",
		"Open", "Not now", answered, g_object_ref(volume));
	g_free(name);
}

void drives_init(void) {
	monitor = g_volume_monitor_get();
	g_signal_connect(monitor, "volume-added", G_CALLBACK(volume_added), NULL);
}
