/*
 * Copyright (C) 2013  Daniel Gröber <dxld ÄT darkboxed DOT org>
 *
 * 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 3 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, see <http://www.gnu.org/licenses/>.
 */

/*
 * This program is a hack so I can make xclip exit after a single paste
 * independent of the target application.
 *
 * It turns out that when you paste into a sane program like a terminal xclip
 * gets a single selection request, which would be fine and I could just use
 * it's `-loop' option to make it exit after one paste. However some silly
 * programs like choromium (and probably others) send at least 6-8 selection
 * requests depending on where in a page or address bar you paste something.
 * The problem with this being that if I use `-loop' to limit xclip to a single
 * selection request it exits and chromium tries to send a couple more, so then
 * it's not actually able to read the clipboard from xclip.
 *
 * Now the only way I could find to make this work consistently is to wait for
 * xclip to output something other than the initial messages when using it's
 * `-verbose' option and that's exactly what this program does.
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/time.h>

#define BUF_SIZE 1024

#define STATE_INIT 0
#define STATE_WAITING 1

struct itimerval it;
volatile sig_atomic_t state;
pid_t pid;


void onalarm(int sig) {
	if(state == STATE_INIT) {
		state = STATE_WAITING;
	} else if(state == STATE_WAITING) {
		kill(pid, SIGPIPE); /* Kill the program on the other end of the
				     * pipe immedietly so it doesn't hang
				     * forever if it doesn't write anything else
				     * to the pipe */
		exit(0);
	}
}

int main(int argc, char** argv) {
	int rv;
	char buf[1024];

	if(argc == 1) {
		printf("usage: output-trigger PID\n");
		exit(1);
	}

	fprintf(stderr, "pid: %s", argv[1]);

	pid = strtol(argv[1], NULL, 10); /* This should be the pid of the
					  * program connected to stdin */



	struct sigaction act = {
		.sa_handler = onalarm,
		.sa_flags = SA_RESTART
	};

	it.it_value.tv_sec = 0;
	it.it_value.tv_usec = 100000;

	rv = sigaction(SIGALRM, &act, NULL);
	if(rv < 0)
		perror("sigaction");


	while(1) {
		ssize_t r = read(STDIN_FILENO, &buf, sizeof(buf));
		if(r < 0)
			perror("read failed");
		else if(r == 0)
			exit(0);

		printf("read: "); fflush(stdout);
		write(STDOUT_FILENO, buf, r);


		setitimer(ITIMER_REAL, &it, NULL);
	}
}
