/* how to validate a password. -jer 980524.1520 */

#include <stdio.h>
#include <stdlib.h>    /* for strncpy */

#include <unistd.h>    /* for crypt(3) */
#include <pwd.h>       /* for getpwnam(3) */
#include <sys/types.h> /* for getpwnam(3) */
#include <errno.h>  /* for errno, ENOMEM */

#include <utmp.h>

void readloginentry (struct utmp *pentry, char *fname);
void printutmpentry (struct utmp *pentry);

int main(void) {
  struct utmp ent;
  readloginentry (&ent, "/var/log/wtmp");
  printutmpentry (&ent);
  printf ("also got here\n");
  return 0;
}

char* uttypes[] = {
  "UT_UNKNOWN", "RUN_LVL", "BOOT_TIME", "NEW_TIME",
  "OLD_TIME",	"INIT_PROCESS",	"LOGIN_PROCESS",
  "USER_PROCESS",	"DEAD_PROCESS"
};

/* read the last entry from file fname into the struct pointed to by pentry */
void readloginentry (struct utmp *pentry, char *fname) {
  FILE *wtmpf = fopen (fname, "r");
  if (wtmpf == NULL) {
    perror ("opening wtmp-style logfile");
    fprintf (stderr, "for file '%s'\n", fname );
  }
  fseek ( wtmpf, - sizeof(struct utmp), SEEK_END);
  fread ( pentry, sizeof(struct utmp), 1, wtmpf );
  fclose (wtmpf);
}

/* output, to stdout, the struct pointed to by pentry
 * in a legible format */
void printutmpentry (struct utmp *pentry) {
  char buf[24];
  int typ;

  typ = pentry->ut_type;
  if ((typ >= 0) && (typ <= 8))
    printf ("type: %s\n", uttypes[typ]);
  else
    printf ("type: %d\n",typ);

  printf (" pid: %d\n", (int) (pentry->ut_pid));
  /*  strncpy (buf, pentry->ut_line, UT_LINESIZE);
  buf[UT_LINESIZE] = '\0';
  printf ("line: %s\n", buf ); */
  printf ("  id: %c%c\n",(int) pentry->ut_id[0], (int) pentry->ut_id[1]);
  printf ("time: %ld\n", (long int) pentry->ut_time);
  /*  strncpy (buf, pentry->ut_user, UT_NAMESIZE);
  buf[UT_NAMESIZE] = '\0';
  /*  printf ("user: %s\n", buf);
  strncpy (buf, pentry->ut_host, UT_HOSTSIZE);
  buf[UT_HOSTSIZE] = '\0';
  /*  printf ("host: %s\n", buf);  */
  printf ("got here\n");
  printf ("addr: %lu\n", pentry->ut_addr);
}
