/*
 *   logtool - a logfile parsing/monitoring/manipulation utility
 *
 *   Copyright (C) Y2K (2000) A.L.Lambert
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2, or (at your option)
 *   any later version.
 *
 *   This program 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 General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the Free Software
 *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include "includes.h"

/* for solaris, which has no setenv, we do this monkey business */
#ifndef HAVE_SETENV
/* prototype */
int local_setenv(char *name, char *val, int clobber);

/* we assume we have getenv and putenv - if we don't, we've got trouble */
int local_setenv(char *name, char *val, int clobber) {

	char   *cp;	/* place for variable we want to set */
	
	/* if this value already exists, and clobber == 0, then don't clobber it */
	if (clobber == 0 && getenv(name) != 0) {
		return 0;
	}
	
	/* malloc some space for cp */
	cp = malloc(strlen(name) + strlen(val) + 2);
	
	/* make sure that worked */
	if (cp == NULL) {
		/* oops - no space for cp - bombs away! */
		return (-1);
	}
	/* setup cp to appropriate NAME=VALUE text */	
	sprintf(cp, "%s=%s", name, val);
	/* return with the value of putenv(cp) for checking by calling program */
	return (putenv(cp));
}
#endif

void strip_space(char *input) {
        int i, j;
	char tmp[LSIZE];
	
        for (i = 0, j = 0 ; input[i] != '\0'; ++i) {
                if(input[i] != ' ') {
                        tmp[j] = input[i];
                        ++j;
                }
        }
	tmp[j] = '\0';
        strcpy(input, tmp);
}


int lt_putenv(char *line) {
        
	long int retval;
	char name[LSIZE];
        char val[LSIZE];
	
	/* strip the line into the name/value var's	*/
	sscanf(line, "%[^=]=%s", name, val);
	/* remove any spaces from the variables		*/
	strip_space(name);
	strip_space(val);
	/* set the environment variable passed as line	*/
	#ifdef HAVE_SETENV
	retval = setenv(name, val, 1);
	#else /* probably a solaris box without setenv  */
	retval = local_setenv(name, val, 1);
	#endif
	/* return to calling function			*/
	return retval;

}

