/*
 * evexec.c:  execute a program when a key has been pressed
 *
 * Copyright (C) 2003 Oliver Endriss (o.endriss@gmx.de)
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 * Or, point your browser to http://www.gnu.org/copyleft/gpl.html
 *
 * Compile:
 * 	gcc -o evexec evexec.c
 *
 * Usage:
 * 	evexec /dev/input/eventX code command
 *
 * Examples:
 * - dump codes:
 *	evexec /dev/input/event0
 *
 * - display "key 47 pressed" if code 47 has been received:
 *	evexec /dev/input/event0 47 "echo key 47 pressed"
 *
 */


#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <linux/input.h>


int main (int argc, char **argv)
{
	int fd, rd, code;
	struct input_event ev[1];

	if (argc != 2 && argc != 4) {
		printf("Usage: evexec /dev/input/eventX code command\n");
		exit(1);
	}

	if ((fd = open(argv[1], O_RDONLY)) < 0) {
		perror("evexec");
		exit(1);
	}

	code = (argc != 2) ? atoi(argv[2]) : 0;

	while (1) {
		rd = read(fd, ev, sizeof ev);

		if (rd < (int) sizeof(struct input_event)) {
			perror("evexec");
			exit (2);
		}

		// printf("evexec: time %ld.%06ld  type %d  code %d  value %d\n",
		//	ev[0].time.tv_sec, ev[0].time.tv_usec, ev[0].type, ev[0].code, ev[0].value);

		if (ev[0].value == 1)
		{
			if (argc == 2)
				printf("evexec: time %ld.%06ld code %d\n",
					ev[0].time.tv_sec, ev[0].time.tv_usec, ev[0].code);

			if (ev[0].code == code)
				system(argv[3]);
		}
	}
}

