/* UNIX like 'last' program. Kees Lemmens; Aug '92

   Shows the contents of the WTMP or BTMP files in the opposite order:
   The user who logged in most recently is showed on the first line.
   The -b option can be used to read BTMP to examine bad logins.

   Any questions or suggestions about this program can be send to:
   lemmens@dv.twi.tudelft.nl
*/

/* define MINT if compiling for MINT, omit for normal ATARI */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "utmp.h"

void usage(void)
{	fputs("\nUsage: last [-b] [-?] <-nr> \n",stderr);
	exit(1);
}

void main(int argc,char *argv[])
{
	char *log [] = { WTMP_FILE, BTMP_FILE };
	char *name[] = { "WTMP", "BTMP" };
	struct utmp *w;
	int mod,max,cnt = -1;
	time_t st_tm;

	max=mod=0;
	while(--argc>0)			/* parse options */
	{	if(*argv[1]=='-')
		{	switch(*(++argv[1]))
			{	case '?':	usage(); break;
				case 'b':	mod=1;   break; /* show last bads */
				default :	max = -atoi(argv[1]);	break;
			}
			++argv;
		}
	}

	utmpname(log[mod]);
	if((w=getutent()) == NULL)
	{	printf("Can't open %s !\n",log[mod]);
		exit(1);
	}
	st_tm=w->ut_time;		/* log time of first entry */

	do						/* start list at end of file */
	{	lseek(utmp_fd,cnt*sizeof(struct utmp),SEEK_END);
		w=getutent();
		printf("%-8s %-*s %2d %2d %s",w->ut_user,
		(int)sizeof(w->ut_line),w->ut_line,w->ut_pid,
		w->ut_type,ctime(&w->ut_time));
		if(st_tm == w->ut_time)
		{	printf("\n%s begins at %s",name[mod],ctime(&st_tm));
			break;	 		/* begin of file reached */
		}
	}while(cnt-- > max || max == 0);

	endutent();
	exit(0);
}
