/*
 * var.c
 *
 * do shell variable stuff
 */

#include <stdio.h>
#include <sys/types.h>
#include "defs.h"
#include "shell.h"

VARS	*vars;

#ifdef notdef
set_var(var, str)
	char   *var,
	       *str;
{
	VARS   *tmp;
	char   *malloc();

	tmp = vars;
	while (tmp) {
		if (!strcmp(tmp->vr_name, var))
			break;
		tmp = tmp->vr_next;
	}

	if (tmp == 0) {		    /* a new variable */
		tmp = (VARS *) malloc((u_int)sizeof(VARS));
		tmp->vr_name = malloc((u_int)strlen(var) + 1);
		strcpy(tmp->vr_name, var);

		tmp->vr_next = vars;
		vars = tmp;
	} else {			    /* the variable just needs to be
					     * changed */
		if (tmp->vr_val)
			free((char *)tmp->vr_val);
	}

	/* set the variable value field */
	if (str == 0)
		tmp->vr_val = 0;
	else {
		tmp->vr_val = malloc((u_int)strlen(str) + 1);
		strcpy(tmp->vr_val, str);
	}
}
#endif

char *
get_var(var)
	char   *var;
{
	VARS   *tmp;

	if (var == 0) {		    /* list all variables */
		for (tmp = vars; tmp; tmp = tmp->vr_next) {
			fprintf(stdout, "%-20s ", tmp->vr_name);
			if (tmp->vr_val)    /* there is a value */
				fprintf(stdout, "= \"%s\"\n", tmp->vr_val);
			else
				putc('\n', stdout);
		}
		return (0);
	}
	/* look for the variable in our list */
	for (tmp = vars; tmp; tmp = tmp->vr_next)
		if (!strcmp(var, tmp->vr_name))
			break;

	if (tmp)			    /* valid varible */
		if (tmp->vr_val)	    /* a valued variable */
			return (tmp->vr_val);	/* the value of the variable */
		else			    /* no value, return something */
			return (" ");	    /* some place-holder */
	else
		return (0);
}

#ifdef notdef

/*
 * Set a variable to s string. 
 */
doset(args)
	char   *args[];
{
	char    line[200];
	int     i;

	if (args[1] == 0) {
		get_var((char *)0);
		return;
	}
	line[0] = '\0';
	for (i = 2; args[i] != 0; i++) {
		strcat(line, args[i]);
		strcat(line, " ");
	}
	if (strlen(line) > 1) {		    /* there is a line */
		line[strlen(line) - 1] = '\0';	/* get rid of trailing space */
		set_var(args[1], line);
	} else
		set_var(args[1], (char *)0);
}


/*
 * Throw away a variable name. 
 */
dounset(args)
	char   *args[];
{
	VARS   *tmp,
	       *last;
	int     i;

	if (args[1] == 0) {
		(void) putline("Unset what?");
		return;
	}
	for (i = 1; args[i]; i++) {
		tmp = vars;
		last = 0;
		while (tmp) {
			if (!strcmp(tmp->vr_name, args[i])) {
				if (last == 0)
					vars = tmp->vr_next;
				else
					last->vr_next = tmp->vr_next;
				free((char *)tmp);
				break;
			}
			last = tmp;
			tmp = tmp->vr_next;
		}
	}
}
#endif
