/*
 * Csh - a shell by PJAC
 * env.c - routines to handle the environment
 */
#include "csh.h"

do_setenv(argc, argv)
char	**argv;
{
	char	*p;
	char	**xp, **oxp, **oxp1;
	int	i;

	if(argc < 3)
		return(OK);
	i = strlen(argv[1]);
	for(xp = Real_Environ ; *xp ; xp++)
		if(strncmp(*xp, argv[1], i) == 0 && (*xp)[i] == '=')
			break;
	if(*xp != 0){
		/* got an old one, replace */
		/* first check to see if we have replaced it already */
		for(oxp = environ ; *oxp ; oxp++)
			if(*oxp == *xp)
				break;
		if(*oxp == 0)
			free(*xp);
	}
	else {
		/* not an old one , must create a new one */
		xp = (char **)mmalloc(sizeof(char *) *(++Nenvir));
		for(oxp = Real_Environ, oxp1 = xp; *oxp;)
			*oxp1++ = *oxp++;
		Real_Environ = xp;
		free( (char *)Real_Environ);
		xp = oxp1++;
		*oxp1 = 0;
	}
	*xp = mmalloc(i + 1 + strlen(argv[2]) + 1);
	strcpy(*xp, argv[1]);
	(*xp)[i] = '=';
	strcpy(*xp + i + 1, argv[2]);
	return(OK);
}

do_u_nsetenv(argc, argv)
char	**argv;
{
	if(argc < 2)
		return(OK);
	argv++;
	while(*argv)
		do__nsetenv(*argv++);
	return(OK);
}

do__nsetenv(str)
char	*str;
{
	char	**xp;
	char	*p;
	int	i;

	i = strlen(str);
	for(xp = Real_Environ ; *xp ; xp++)
		if(strncmp(*xp, str, i) == 0 && (*xp)[i] == '=')
			break;
	if(*xp == 0)	/* not found, ignore */
		return;
	p = *xp;
	/* pull the environ down a bit */
	while(*xp){
		*xp = *(xp+1);
		xp++;
	}
	Nenvir--;	/* we have less in the environment */
			/* is this an original env string ?? */
	for(xp = environ ; *xp ; xp++)
		if(*xp == p)
			break;
	if(!*xp)		/* if not then can free it */
		free(p);
	return(OK);
}
