/*
 * USERLIST
 * Display management routines
 */

#include "userlist.h"
#include "proto.h"

char *inettos(long addr)
{
    char *ret; 
    int p1, p2, p3, p4;

    ret = (char *) malloc(20);
    p1 = (addr & 0x000000FF);
    p2 = (addr & 0x0000FF00) >> 8;
    p3 = (addr & 0x00FF0000) >> 16;
    p4 = (addr & 0xFF000000) >> 24;

    sprintf(ret, "%d.%d.%d.%d", p1, p2, p3, p4);
    return(ret);
}

char *get_localhost(void)
{
#ifndef	LOCAL_NAME
    char *ret;
    char hostname[STRLEN];
    char *p;

    memset(hostname, 0, STRLEN);

    gethostname((char *) hostname, (size_t) STRLEN);
    if ((p = index(hostname, '.')) != NULL)
      *p = '\0';

    ret = (char *) malloc(strlen((char *) hostname) + 1);

    sprintf(ret, "%s", (char *) hostname);
    return(ret);
#else
    return(LOCAL_NAME);
#endif
}

int exist(const char *filename)
{
    FILE *file;

    file = fopen(filename, "r");
    if (file) {
	fclose(file);
	return(1);
    } else
	return(0);
}

void process_display(void)
{
    int i;
    char *our_host;
    char *idle;

    our_host = get_localhost();
    if (times_on == 0) {
	printf ("Nobody logged in.\n");
	return;
    } else
	printf ("USERNAME Real name                      Idletime TTY Remote console location\n");

    for (i = 0; (i < times_on) && (i < MAX_TTYS); i++) {
	char console[30];
	struct passwd *pwent;

	if (strlen((char *) tty_list[i].locale) == 0)
	    snprintf(console, sizeof(console), "(%s)", our_host);
	else
	    snprintf(console, sizeof(console), "(%s)", tty_list[i].locale);

	if (strlen((char *) tty_list[i].username) > 1) {
	    char *username=NULL;
	    char ru[8], fn[STRLEN];

	    memset(ru, 0, sizeof (ru));
	    memset(fn, 0, sizeof (fn));

	    strncpy(ru, tty_list[i].username, sizeof(ru)-1);

	    pwent = getpwnam((char *) ru);

	    if (pwent) {
		cp = pwent->pw_gecos;
		if ((x = index (pwent->pw_gecos, ',')) != NULL) /* username */
		    *x = '\0';
		    if ((username = (char *)malloc (strlen(cp)+1)) != NULL) {
			memset (username, 0, strlen(cp)+1);
			strcpy (username, cp);
		    }
		snprintf(fn, sizeof(fn), "%s/.nofinger", pwent->pw_dir);
	    }

	    idle = calc_idle((char *) tty_list[i].line);
	    if (pwent) {
		if (!exist((char *) fn)) {
		    if (idle) {
			printf("%-8.8s %-30.30s %8.8s ",
			       ru, username?username:"", idle);

			printf("%3.3s %-25.25s\n",
			       (char *) tty_list[i].tty, console);
		    }
		}
	    } else {
		if (idle) {
		    printf("%-8.8s %-30.30s %8.8s ",
			   ru, ru, idle);

		    printf("%3.3s %-25.25s\n",
			   (char *) tty_list[i].tty, console);
		}
	    }
	}

	fflush(stdout);
    }
}

/*
 * Local variables:
 *  c-indent-level: 4
 *  c-basic-offset: 4
 *  tab-width: 8
 * End:
 */
