/*
 * check-foreground-console: A tool to check if the current console is owned
 * by the calling user.
 *
 * Copyright 2006 Daniel Silverstone <daniel.silverstone@ubuntu.com>
 *
 * Licence: GPL v2 (but not later)
 */

#define CONSOLEDIR "/var/run/console"
#define FILEPATTERN "%s/%s:%d"
#define DIEIF(X) if ((X)) return 2;

#include <limits.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <linux/vt.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <pwd.h>
#include <string.h>
#include <stdio.h>

int main(int argc, char **argv)
{
	char buffer[PATH_MAX];
	char *username;
	int fgvt;
	int fd;
	struct vt_stat vtstat;
	struct passwd *userinfo;

	fd = open("/dev/console", O_RDWR);
	DIEIF((fd < 1));
	DIEIF((ioctl(fd, VT_GETSTATE, &vtstat)));
	close(fd);
	fgvt = vtstat.v_active;
	DIEIF((fgvt > 99));

	userinfo = getpwuid(getuid());
	username = userinfo->pw_name;

	/* All gathered together */	
	snprintf(buffer, PATH_MAX, FILEPATTERN, CONSOLEDIR, username, fgvt);

	return ((open(buffer, O_RDONLY)) == -1);
	
}
