/*
 * Copyright (C) 2022 Guido Berhoerster <guido+ubports@berhoerster.name>
 *
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 3, as published
 * by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranties of
 * MERCHANTABILITY, SATISFACTORY QUALITY, 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 this program.  If not, see <http://www.gnu.org/licenses/>.
 */
/*
 * invoked by lomiri-app-launch in order to look up the unprivileged helper
 * of a click app
 */
#include <stdlib.h>

#include <glib.h>
#include <lomiri-app-launch.h>

#include "find-helper.h"

int
main(int argc, char *argv[])
{
	int		status = EXIT_FAILURE;
	const gchar	*app_id;
	gchar		*package = NULL;
	gchar		*app = NULL;
	GError		*error = NULL;
	gchar		*exec_value = NULL;

	/*
	 * application ID for which the unprivileged helper needs to be lloked
	 * up
	 */
	app_id = g_getenv("APP_ID");
	if (app_id == NULL) {
		g_critical("no application ID passed via APP_ID");
		goto out;
	}

	if (!lomiri_app_launch_app_id_parse(app_id, &package, &app, NULL)) {
		g_critical("invalid application ID: %s", app_id);
		goto out;
	}

	exec_value = find_helper(package, app, &error);
	if (exec_value == NULL) {
		g_critical("%s", error->message);
		g_error_free(error);
		goto out;
	}

	if (!lomiri_app_launch_helper_set_exec(exec_value, NULL)) {
		g_critical("failed to set exec line for untrusted helper tool");
		goto out;
	}

	status = EXIT_SUCCESS;

out:
	g_free(app);
	g_free(package);
	g_free(exec_value);

	exit(status);
}
