/*
 * This file is part of roccat-tools.
 *
 * roccat-tools is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * roccat-tools is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with roccat-tools. If not, see <http://www.gnu.org/licenses/>.
 */

#include "roccat/roccat.h"
#include "roccat_eventhandler_application.h"
#include "dbus_roccat_helper.h"
#include <glib.h>
#include <stdlib.h>

static GOptionContext *commandline_parse(int *argc, char ***argv) {
	GOptionContext *context = NULL;
	GError *error = NULL;

	context = g_option_context_new("- handle extended capabilities of Roccat devices");

	if (!g_option_context_parse(context, argc, argv, &error)) {
		g_critical("option parsing failed: %s", error->message);
		exit(EXIT_FAILURE);
	}
	return context;
}

static void commandline_free(GOptionContext *context) {
	g_option_context_free(context);
}

int main(int argc, char **argv) {
	GOptionContext *context;
	GMainLoop *loop;
	gint retval = EXIT_SUCCESS;
	RoccatEventhandlerApplication *app;
	gboolean unique;

	roccat_secure();

#if !(GLIB_CHECK_VERSION(2, 36, 0))
	g_type_init();
#endif

	context = commandline_parse(&argc, &argv);

	dbus_roccat_register_service(ROCCAT_DBUS_SERVER_NAME, &unique);
	if (!unique) {
		g_debug("There is already an instance running");
		exit(EXIT_FAILURE);
	}

	app = roccat_eventhandler_application_new();

	loop = g_main_loop_new(NULL, FALSE);
	g_main_loop_run(loop);

	g_object_unref(app);
	commandline_free(context);
	exit(retval);
}
