/*
 * USERLIST
 * Show user idletime
 */

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

#include <sys/stat.h>
#include <unistd.h>
#include <time.h>

char *calc_idle(char *tty)
{
    struct stat buf;
    time_t cur_time;
    long diff_time;
    int min, hour, day;
    static char idledisp[STRLEN];
    char dev_file[STRLEN];

    memset(idledisp, 0, sizeof (idledisp));
    memset(dev_file, 0, sizeof (dev_file));

    snprintf(dev_file, sizeof (dev_file), "/dev/%s", tty);

    stat((char *) dev_file, &buf);
    cur_time = time(NULL);

    diff_time = (long) cur_time - (long) buf.st_mtime;

    min = hour = day = 0;

    if (diff_time > 86400)
	day = hour = 1;
    else if (diff_time > 3600)
	hour = min = 1;
    else if (diff_time > 59)
	min = 1;

    if (day) {
	day = diff_time / 86400;
	diff_time -= day * 86400;
    }

    if (day) {
	if (no_idle) return NULL;
	snprintf(idledisp, sizeof (idledisp), "%1dd ", day);
	return idledisp;
    }

    if (hour) {
	hour = diff_time / 3600;
	diff_time -= hour * 3600;
    }

    if (min) {
	min = diff_time / 60;
	diff_time -= min * 60;
    }

    if (hour || min) {
	if (day)
	    snprintf(idledisp, sizeof (idledisp), "%02d:%02d", hour, min);
	else
	    snprintf(idledisp, sizeof (idledisp), "%d:%02d", hour, min);
    }

    return idledisp;
}

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