#include	<stdio.h>
#include	<stdlib.h>
#include	<utmp.h>
#include	<fcntl.h>
#include	<unistd.h>
#include	<time.h>
#include	<string.h>

#define	SHOWHOST	/* include remote machine on output */
char * showtime(time_t t);
void show_info( struct utmp *utbufp, short int whoAmI );

int main(int argc, char ** argv)
{
	struct utmp	current_record;	/* read info into here       */
	int		utmpfd;		/* read from this descriptor */
	int		reclen = sizeof(current_record);
	short int whoAmI = 0;
/*
	printf("argc: %i\n", argc);
	if (argc == 3)
	{
		printf("argv[0]: %s\n", argv[0]);
		printf("argv[1]: %s\n", argv[1]);
		printf("argv[2]: %s\n", argv[2]);
	}
*/
	if (argc == 3 && (strcmp(argv[1], "am") == 0)&& (strcmp(argv[2], "i") == 0))
	{
		whoAmI = 1;
	}
	
	if ( (utmpfd = open(UTMP_FILE, O_RDONLY)) == -1 ){
		perror( UTMP_FILE );	/* UTMP_FILE is in utmp.h    */
		exit(1);
	}

	while ( read(utmpfd, &current_record, reclen) == reclen )
		show_info(&current_record, whoAmI);
	close(utmpfd);
	return(0);
}

/*
 *  show info()
 *	displays contents of the utmp struct in human readable form
 *	*note* these sizes should not be hardwired
 */
void show_info( struct utmp *utbufp, short int whoAmI )
{
	char * myTty = ttyname(0);
	if (utbufp->ut_type != USER_PROCESS) return;
	if (whoAmI == 1 && (strcmp(myTty + 5, (char *) utbufp->ut_line) != 0)) return;
	printf("%-8.8s", utbufp->ut_name);	/* the logname	*/
	printf(" ");				/* a space	*/
	printf("%-8.8s", utbufp->ut_line);	/* the tty	*/
	printf(" ");				/* a space	*/
	printf("%10s", showtime((time_t)utbufp->ut_time));/* login time	*/
	printf(" ");				/* a space	*/
#ifdef	SHOWHOST
	printf("(%s)", utbufp->ut_host);	/* the host	*/
#endif
	printf("\n");				/* newline	*/
	return;
}

char * showtime(time_t t)
{
	size_t bufSize = 15;
	char * buf = malloc(bufSize * sizeof(char));
	struct tm * tm;
	tm = localtime(&t);
	strftime(buf, bufSize, "%b %m %H:%M", tm);
	return buf;
}
