/*
 * $Id: wtmp-gate.c,v 1.7 1998/12/10 10:04:36 agalat Rel $
 */

#include <utmp.h>
#include <unistd.h>
#include <malloc.h>

#include <pniam.h>

#include "../../common/include/wtmp.h"
#include "../include/wtmp-gate.h"
#include "../include/get_item.h"

/*
 * Returns:
 *   0     ok,
 *   1     non-fatal error
 *  -1     fatal error
 *  callname and err_descr will be set
 * Be carefull: the function indirectly uses alarm().
 */
int utmp_open_session(pniam_item_list_t *list, pid_t pid
                             , const char **callname, const char **err_descr)
{
    const char *terminal;
    char *user, *rhost;
    pniam_result_t res;
    int retval;

    terminal = ttyname(STDIN_FILENO);
    res = get_item (list, "USER", &user);
    if (res != PNIAM_OK)
    {
        *callname = "pniam_item_list_find(.., 'USER')";
        *err_descr = "Failed to find the username";
        return -1;
    }
    rhost = "localhost";
    retval = utmp_do_open_session(user, terminal, rhost, pid, 
                                        callname, err_descr);
    free (user);
    return retval;
}

int utmp_close_session(const char **callname, const char **err_descr)
{
    const char *terminal;

    terminal = ttyname(STDIN_FILENO);

    return
        utmp_do_close_session(terminal, callname, err_descr);
}
