#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <syslog.h>
#include <termios.h>
#include <unistd.h>
#include <signal.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <sys/utsname.h>

#ifndef N_CHATBOARD
#define N_CHATBOARD 12
#endif

#if 1
#define syslog fprintf
#undef LOG_ERR
#define LOG_ERR stderr
#endif

int main(int argc, char * argv[])
{
	int fd;
	int lastdisc;
	int chatboarddisc = N_CHATBOARD;
	struct termios ti;

	if (argc != 2) {
		syslog(LOG_ERR, "chatboardattach: missing filename\n");
		return -1;
	}
	fd = open(argv[1], O_RDWR | O_EXCL);
	if (fd == -1) {
		syslog(LOG_ERR, "chatboardattach: open(): %s\n",
			strerror(errno));
		return -1;
	}
	ti.c_cflag = CS8|CREAD|B9600|CLOCAL;
	ti.c_iflag = IGNBRK | IGNPAR | ICRNL;
	ti.c_oflag = ONLCR;
	ti.c_lflag = 0;
	ti.c_cc[VMIN] = 1;
	ti.c_cc[VTIME] = 0;
	if (tcsetattr(fd, TCSANOW, &ti) < 0) {
		syslog(LOG_ERR, "chatboardattach: tcsetattr(): %s\n",
			strerror(errno));
	}

	fcntl (fd, F_SETFL, (fcntl(fd, F_GETFL) & ~O_NONBLOCK));

	if (ioctl(fd, TIOCGETD, &lastdisc) < 0) {
		syslog(LOG_ERR, "chatboardattach: get_disc(): %s\n",
			strerror(errno));
		return -1;
	}
	if (ioctl(fd, TIOCSETD, &chatboarddisc) < 0) {
		syslog(LOG_ERR, "chatboardattach: set_disc(): %s\n",
			strerror(errno));
		return -1;
	}
	while (1)
		sleep(2);
	ioctl(fd, TIOCSETD, &chatboarddisc);
}
