/*
 * $Id: make_env.c,v 1.6 1998/11/25 12:33:32 saw Rel $
 */

#include <stdlib.h>

#include <security/pam_appl.h>
#include <security/pam_misc.h>

#include "../include/make_env.h"

/*
 * construct environment for PAM (and hence the shell)
 */

extern char **environ;

/*
 * We will attempt to transcribe the following env variables
 * independent of whether we keep the whole environment. Others will
 * be set elsewhere: either in modules; or after the identity of the
 * user is known.
 */

const char *posix_env[] = {
    "LANG",
    "LC_COLLATE",
    "LC_CTYPE",
    "LC_MONETARY",
    "LC_NUMERIC",
    "TZ",
    NULL
};

int make_environment(pam_handle_t *pamh, int keep_env)
{
    int retval;

    if (keep_env) {

	/* preserve the original environment */
	retval = pam_misc_paste_env(pamh, (const char * const *)environ);

    } else {
	const char *tmpe;
	int i;

	/* we always transcribe some variables anyway */
	{
	    tmpe = getenv("TERM");
	    if (tmpe == NULL) {
		tmpe = "dumb";
	    }
	    retval = pam_misc_setenv(pamh, "TERM", tmpe, 0);
	    tmpe = NULL;
	    if (retval == PAM_SUCCESS) {
		retval = pam_misc_setenv(pamh, "PATH", "/bin:/usr/bin", 0);
	    }

	    if (retval != PAM_SUCCESS) {
		D(("error setting environment variables"));
		return retval;
	    }
	}

	/* also propogate the POSIX specific ones */
	for (i=0; retval == PAM_SUCCESS && posix_env[i]; ++i) {
	    tmpe = getenv(posix_env[i]);
	    if (tmpe != NULL) {
		retval = pam_misc_setenv(pamh, posix_env[i], tmpe, 0);
	    }
	}
	tmpe = NULL;
    }

    return retval;                                   /* how did we do? */
}

