/*
 * Copyright (C) Birb Developers
 *
 * Birb is the legal property of its developers, whose names are too numerous
 * to list here. Please refer to the AUTHORS file distributed with this source
 * distribution
 *
 * This library is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by the
 * Free Software Foundation; either version 2.1 of the License, or (at your
 * option) any later version.
 *
 * This library 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 Lesser General Public License
 * for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this library; if not, see <https://www.gnu.org/licenses/>.
 */

#include "birbenv.h"

/******************************************************************************
 * Public API
 *****************************************************************************/
gboolean
birb_env_append(const char *variable, const char *value, const char *separator)
{
	const char * existing = NULL;
	gboolean ret = FALSE;

	g_return_val_if_fail(variable != NULL, FALSE);
	g_return_val_if_fail(variable[0] != '\0', FALSE);
	g_return_val_if_fail(value != NULL, FALSE);
	g_return_val_if_fail(separator != NULL, FALSE);

	existing = g_getenv(variable);
	if(existing != NULL) {
		char *new_value = NULL;

		new_value = g_build_path(separator, existing, value, NULL);

		ret = g_setenv(variable, new_value, TRUE);
		g_free(new_value);
	} else {
		ret = g_setenv(variable, value, TRUE);
	}

	return ret;
}

gboolean
birb_env_prepend(const char *variable, const char *value,
                 const char *separator)
{
	const char *existing = NULL;
	gboolean ret = FALSE;

	g_return_val_if_fail(variable != NULL, FALSE);
	g_return_val_if_fail(variable[0] != '\0', FALSE);
	g_return_val_if_fail(value != NULL, FALSE);
	g_return_val_if_fail(separator != NULL, FALSE);

	existing = g_getenv(variable);
	if(existing != NULL) {
		char *new_value = NULL;

		new_value = g_build_path(separator, value, existing, NULL);

		ret = g_setenv(variable, new_value, TRUE);
		g_free(new_value);
	} else {
		ret = g_setenv(variable, value, TRUE);
	}

	return ret;
}
