#include <stdio.h>
#include <sys/types.h>
#include <sys/file.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <ttyent.h>
#include <utmp.h>
#include <errno.h>

#define UTMPFILE	"/etc/utmp"

int locking = 1; /* XXX add command line opt */
int allowttys = 0;
int utmpfd;
char *prog;

#define MAX(x,y) ((x > y) ? x : y)

openutmp()
{
  utmpfd = open(UTMPFILE, O_RDWR, 0);
  if (utmpfd == -1)
    {
      fprintf(stderr, "%s: error %d opening utmp\n", prog, errno);
      exit(2);
    }
}

rm(name)
     char *name;
{
  struct utmp ut, ut1;
  time_t time();
  int cc;
  char input[5];
  off_t ptr;
  /* lets see if we can get this program to work on 8-char usernames */
  char new_name[8];

  bzero(new_name, sizeof(char) * 8);
  strncpy(new_name, name, 8);

  ptr = 0;

  lseek(utmpfd, ptr, L_SET);
  while ((cc = read(utmpfd, &ut, sizeof(ut))) == sizeof(ut))
    {
      if (allowttys || !strncmp("ftp", ut.ut_line, 3))
	{
	  if (!strncmp(new_name, ut.ut_name, 8))
	    {
	      fprintf(stdout, "remove %.8s %.8s %.12s (%.16s)? ",
		      ut.ut_name, ut.ut_line, &ctime(&ut.ut_time)[4],
		      ut.ut_host);

	      fgets(input, sizeof(input), stdin);
	      if (input[0] == 'y' || input[0] == 'Y')
		{
		  if (locking)
		    flock(utmpfd, LOCK_EX);
		  lseek(utmpfd, ptr, L_SET);
		  if ((cc = read(utmpfd, &ut1, sizeof(ut1))) == sizeof(ut1))
		    {
		      if (!bcmp(&ut, &ut1, sizeof(ut)))
			{
			  bzero(ut.ut_name, sizeof(ut.ut_name));
			  bzero(ut.ut_host, sizeof(ut.ut_host));
			  time(&ut.ut_time);
			  lseek(utmpfd, ptr, L_SET);
			  cc = write(utmpfd, &ut, sizeof(ut));
			  if (cc != sizeof(ut))
			    {
			      fprintf(stderr, "%s: error %d writing utmp\n",
				      prog, errno);
			      exit(2);
			    }
			  if (locking)
			    flock(utmpfd, LOCK_UN);
			}
		      else
			fprintf(stderr,
			      "%s: entry changed before it could be removed\n",
			      prog);
		    }
		  else
		    {
		      fprintf(stderr, "%s: error %d reading utmp\n",
			      prog, errno);
		      exit(3);
		    }
		}
	    }
	}
	ptr += cc;
      }
}

usage()
{
  fprintf(stderr, "usage: %s [-nolock] [-ttys] username ...\n", prog);
  exit(1);
}

main(argc, argv)
     int argc;
     char **argv;
{
  char **arg;

  prog = argv[0];

  for (arg = argv + 1; *arg != NULL; arg++)
    {
      if (**arg == '-')
	{
	  if (!strcmp(*arg, "-nolock"))
	    locking = 0;
	  else	    
	    if (!strcmp(*arg, "-ttys"))
	      allowttys = 1;
	  else
	    usage();
	}
      else
	break;
    }

  openutmp();

  for (; *arg != NULL; arg++)
    rm(*arg);
}
