#include <sys/stat.h>
#include "sysinfo_defs.h"
#include "boottime_defs.h"

#if !defined(HAVE_SYSTEM_SYSINFO) && !defined(HAVE_SYSTEM_BOOTTIME)
int check_first(char *lock, struct stat *st) { return 0; }

#else
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <time.h>
extern int get_uptime(time_t *t);

int check_first(char *lock, struct stat *st) /*EXTRACT_INCL*/{
  int k;
  /* If a stat error other than "no such file" occurs, I don't
     know what went wrong, so I'll proceed with caution by
     denying the autologin request. */
  if ((k=stat(lock, st)) && errno != ENOENT)
    return 0;

  if (k==0) {
    time_t uptime;
    if (get_uptime(&uptime))
      return 0;
 
    /* If there's been an autologin granted since the last boot,
       deny this and any subsequent attempts.  Note that this test
       is skipped if the LOCK file doesn't exist. */
    if (time(0) - uptime < st->st_mtime)
      return 0;
  }

  /* Create the LOCK file.  The mtime of this file provides
     a persistent record of the last time that an autologin
     request was granted.  Deny the autologin request if either
     the file open or file close fails. */
  if ((k=open(lock, O_WRONLY|O_CREAT|O_TRUNC, 0644)) < 0 || close(k))
    return 0;

  /* All tests are okay, so grant the autologin request. */
  return 1;
}
#endif
