/*
** 1998-11-25 -	A little module to take care of startup options (arguments to
**		main()). This will probably evolve into, or (preferably), get
**		replaced by getopt() or something later on.
*/

#include "gentoo.h"

#include <stdlib.h>

#include "options.h"

/* ----------------------------------------------------------------------------------------- */

typedef struct {
	char	*name;
	guint32	flag;
} OptDef;

static OptDef	opt_def[] = {	{"root-ok", OPTF_ROOT_OK},	{"version", OPTF_VERSION},
				{"no-rc", OPTF_NO_RC},		{"no-gtkrc", OPTF_NO_GTKRC} };

/* ----------------------------------------------------------------------------------------- */

/* 1998-11-25 -	Remove the <index>'th argument from the <argv>-vector, and also update
**		<argc> accordingly.
*/
static void opt_remove(int *argc, char **argv, int index)
{
	int	i;

	if(argc == NULL || argv == NULL || index < 0 || index >= *argc)
		return;

	for(i = index; argv[i] != NULL; i++)
		argv[i] = argv[i + 1];
	(*argc)--;
}

/* ----------------------------------------------------------------------------------------- */

/* 1998-11-25 -	Extract the known options from the arguments described by <argc> and <argv>.
**		Note that this function will *modify* the argument description when known
**		options are found, removing them from the vector. I don't *think* that's
**		a problem (gtk_init() does the same thing), but since I don't have the
**		ANSI C standard handy, I don't really know. All I know is that they're not
**		const-declared by main(), and this code doesn't segfault under Linux...
** 1999-01-09 -	Modified, now it returns the flags found, so caller can inspect them too.
*/
guint32 opt_extract(int *argc, char **argv)
{
	guint	i, j, found;
	guint32	flags = 0U;

	if(argc == NULL || argv == NULL)
		return 0U;

	for(i = 1; argv[i] != NULL;)
	{
		found = 0;
		if(argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] != '\0')
		{
			for(j = 0; j < sizeof opt_def / sizeof opt_def[0]; j++)
			{
				if(strcmp(argv[i] + 2, opt_def[j].name) == 0)
				{
					opt_remove(argc, argv, i);
					flags |= opt_def[j].flag;
					found = 1;
					break;
				}
			}
			if(!found)
				fprintf(stderr, "%s: Unknown option '%s'\n", argv[0], argv[i]);
		}
		if(!found)
			i++;
	}
	if(!(flags & OPTF_ROOT_OK) && geteuid() == 0)
	{
		fprintf(stderr, "%s: To run as root, envoke with the '--root-ok' option\n", argv[0]);
		exit(EXIT_FAILURE);
	}
	if(flags & OPTF_VERSION)
	{
		fprintf(stdout, "%s\n", VERSION);
		exit(EXIT_SUCCESS);
	}

	return flags;
}
