/* 100% based on irattach 1.1 by Dag Brattli. Bugs are mine. Milan Pikula <www@fornax.sk> */

#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_IRDA
#define N_IRDA 11
#endif

#ifndef AF_IRDA
#define AF_IRDA 23
#endif

#define IRTTY_IOC_MAGIC 'e'
#define IRTTY_IOCGNAME   _IOR(IRTTY_IOC_MAGIC, 2, struct irtty_info)

struct irtty_info {
	char name[6];
};

int main(int argc, char * argv[])
{
	int fd;
	int irdadisc = N_IRDA;
	struct termios ti;
	struct irtty_info inf;
	char command[64];

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

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

	if (ioctl(fd, TIOCSETD, &irdadisc) < 0) {
		syslog(LOG_ERR, "wirattach: set_disc(): %s\n",
			strerror(errno));
		return -1;
	}
	/* now we have ir device, we should turn it UP */
	if (ioctl(fd, IRTTY_IOCGNAME, &inf) < 0) {
		syslog(LOG_ERR, "wirattach: ir_get_name(): %s\n",
			strerror(errno));
		return -1;
	}

	sprintf(command, "/sbin/ifconfig %s up", inf.name);
	system(command);
	
	if (fork())
		return 0;

	setsid();
	
	while (1)
		sleep(20);
}
