#include "lib.h"

#define SD(A,B) !str_diffn(A, B, sizeof(A))
#define SC(A,B) str_copynz(A, B, sizeof(A))

#if 0
/*EXTRACT_START*/
SC(u.ut_line, line);
if (u.ut_id[0]==0) SC(u.ut_id, p);

if (login) {
  u.ut_type=LOGIN_PROCESS;
  u.ut_pid=getpid();
  p="LOGIN";
} else {
  if (u.ut_type == DEAD_PROCESS) do_wtmp =0;
  u.ut_type=DEAD_PROCESS;
  p="";
}

SC(u.ut_user,p);
SC(u.ut_host,"");
u.ut_tv.tv_sec = time(0);
/*EXTRACT_END*/
#endif

#ifdef USE_LIBC_UTMP
void utmp_do(int login, char *line) { 
  struct utmp_type u, *ut;
  char foundone=0, do_wtmp=1;
  char *p;

  p=line;
  while (str_len(p) > sizeof u.ut_id) p++;

  str_copynz((char *)&u,"",sizeof(u));
  f_setutent();
  while (f_getutent())
    if ((INIT_PROCESS <= ut->ut_type && 
	 ut->ut_type <= DEAD_PROCESS &&
	 SD(ut->ut_id, p)) || SD(ut->ut_line, line))
      { u = *ut; foundone=1; break; }

#include "utmp_defs.h"

  if (foundone || login) {
    f_setutent(); /* comment this ? */
    f_pututline(&u);
  }
  f_endutent();

  if (do_wtmp)
    f_updwtmp(Wtmp_File, &u);
}

#else
#include <unistd.h>
#include <fcntl.h>

/* line tty5 */
void utmp_do(int login, char *line) /*EXTRACT_INCL*/{ 
  struct utmp_type u;
  char foundone=0, do_wtmp=1;
  int fd=open(Utmp_File, O_RDWR);
  off_t pos=0;
  char *p;

  p=line;
  while (str_len(p) > sizeof u.ut_id) p++;

  while (utmp_io(fd, &u, F_RDLCK)) {
    if ((INIT_PROCESS <= u.ut_type && 
	 u.ut_type <= DEAD_PROCESS &&
	 SD(u.ut_id, p)) || SD(u.ut_line, line)) { foundone=1; break; }
    pos += UTMP_SIZE;
  }

  if (!foundone) {
    str_copynz((char *)&u,"",sizeof(u));
    pos = lseek(fd,0,SEEK_END);
    if (pos<0) pos =0;
    pos = pos - (pos % (UTMP_SIZE));
  }

#include "utmp_defs.h"

  if (foundone || login)
    if (lseek(fd,pos,SEEK_SET) == pos)
      utmp_io(fd,&u,F_WRLCK);
  close(fd);

  if (do_wtmp) {
    fd=open(Wtmp_File, O_WRONLY|O_APPEND);
    write(fd, &u, UTMP_SIZE);
    close(fd);
  }
}
#endif
