#ifndef lint
static char *sccsid = "@(#)lastlog.c	1.1 (UKC) 11/11/87";
#endif  lint
/*
 *	LASTLOG: display contents of /usr/adm/lastlog in ascii format
 *
 *	----- Extract from header file -----
 *	lastlog.h	1.2	(UKC)	7/2/86
 *
 *	struct lastlog {
 *		time_t	ll_time;
 *		char	ll_line[8];
 *		char	ll_host[32];	Enough to fill 80-char line in finger
 *	};
 *	------------------------------------
 */

#include <stdio.h>
#include <sys/types.h>
#include <lastlog.h>
#include <pwd.h>

static void pwprint();

static char llname[] = "/usr/adm/lastlog";
static FILE *llfp;		/* file pointer open to lastlog */

main(argc,argv)
char **argv;
{
	int i;			/* for indexing arguments */
	struct passwd *pwent;
	struct passwd *getpwnam();


	if ( (llfp = fopen(llname, "r")) == NULL) {
		fprintf(stderr, "lastlog: Cannot open \"%s\".\n", llname);
		exit(1);
	}

	switch (argc) {
	case 0: /* ? */
	case 1:
		/* No arguments: show info for all users */
		setpwent();
		while ((pwent = getpwent()) != NULL) {
			pwprint(pwent);
		}
		endpwent();
		break;

	default:
		for (i = 1; i < argc; i++) {
			pwent = getpwnam(argv[i]);
			if (pwent == NULL) {
				fprintf(stderr, "lastlog: \"%s\": no such user.\n", argv[i]);
				continue;
			}

			pwprint(pwent);
		}
		break;
	}
	exit(0);
}

/* print lastlog entry, given user's password structure */
static void
pwprint(pwent)
struct passwd *pwent;
{
	struct lastlog llbuf;
	char *ctime();
	char *lltime;

	if (fseek(llfp, pwent->pw_uid*sizeof(struct lastlog), 0) == -1
	 || fread((char *) &llbuf, sizeof(llbuf), 1, llfp) == 0) {
		/* never logged in, and past end of lastlog */
		llbuf.ll_time = 0L;
		llbuf.ll_line[0] = '\0';
		llbuf.ll_host[0] = '\0';
	}

	/* get time string and poke out the newline */
	lltime = ctime(&(llbuf.ll_time));
	lltime[24] = '\0';

	printf("%s\t%s\t%.*s\t%.*s\n",
		pwent->pw_name,
		lltime + 4,	/* lose day of week */
		sizeof(llbuf.ll_line),
		llbuf.ll_line,
		sizeof(llbuf.ll_host),
		llbuf.ll_host);
}
