/*-
 * Copyright (c) 2005,2006 Peter Wemm
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * $Id: autosource.c,v 1.3 2006/04/11 08:43:55 peter Exp peter $
 */

/*
 * I'm sorry, this was such a quick and dirty hack that I didn't document
 * any of it.
 * What this does is talk to my Global Cache GC-100, with a GC-IRE device
 * listening to my hardwired IR network.  When it sees the tivo IR codes
 * (there are two of them, this has to distinguish between them) or the
 * dvd/mpeg player remote, it transmits a code to the Denon AV receiver to
 * select the appropriate source.
 *
 * Quirks:
 * It has to remember which one it last selected, or it floods the network.
 * Power on/off with the wrong remote will mess up the state, so it has to
 *  send the selection commands each time it sees a power button push.
 * The tivo and the dvd player seem to use the same IR chipset in their
 *  remotes, just with a different device ID.
 * It has to differentiate two tivos (we have one remote with a switch).
 * If we press the 'window' button on the tivo remote, it resends the
 *  input selector signal in case of the (rare) event drop
 * Power-on takes a bit, so there is a delay sending the input selection
 *  after a power button event to make sure it isn't too early.
 * The DVD remote is not "universal", so we have to use the volume/mute
 *  buttons on the tivo.  Also, if we have to grab a remote in a hurry to
 *  cut the volume, we didn't want that messing with the input sources.  So,
 *  volume up/down/mute don't change the input.
 * Various IR strings are hard coded. Too bad. :-)
 */
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/event.h>
#include <err.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <ctype.h>
#include <stdarg.h>
#include <syslog.h>

int debug;
int sc;
int active = 0;
int sendbusy;
int sendwait;
char cmd[1024];

int tivosig[] = {
	1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0
};
int vidsig[] = {
	1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1
};


char sel1[] =
"10,30,10,70,10,30,10,30,10,30,10,70,10,70,10,30,10,30,10,30,10,70,10,70,10,70,10,30,10,30,10,1707,10,30,10,70,10,30,10,30,10,30,10,30,10,30,10,70,10,70,10,70,10,30,10,30,10,30,10,70,10,70,10,1707";

char sel4[] = 
/* -------------------------------^^----^^..............................................^^------- */
"10,30,10,70,10,30,10,30,10,30,10,70,10,30,10,30,10,70,10,30,10,30,10,70,10,70,10,30,10,30,10,1747,10,30,10,70,10,30,10,30,10,30,10,30,10,70,10,70,10,30,10,70,10,70,10,30,10,30,10,70,10,70,10,1667";

char sel5[] =
"10,31,10,71,10,30,10,30,10,30,10,30,10,30,10,70,10,71,10,30,10,30,10,71,10,71,10,30,10,30,10,1763,10,30,10,71,10,30,10,30,10,30,10,71,10,71,10,30,10,30,10,70,10,71,10,30,10,30,10,71,10,71,10,1682";

void
db(char *fmt, ...)
{
	va_list ap;

	va_start(ap, fmt);
	if (debug)
		vprintf(fmt, ap);
	va_end(ap);
}

void
pc(int sc, char *s)
{

	sprintf(cmd, "sendir,2:1,12345,38000,3,1,%s\r", s);
	db("send: '%s'\n", cmd);
	if (sendbusy) {
		db("busy");
		sendwait = 1;
	} else {
		sendbusy = 1;
		write(sc, cmd, strlen(cmd));
	}
}

void
setavr(int avr)
{
	syslog(LOG_INFO, "changing AVR to %d", avr);
	switch (avr) {
	case 1:
		db("CHANGE AVR to 1\n");
		usleep(300 * 1000);
		pc(sc, sel1);
		active = 1;
		break;
	case 4:
		db("CHANGE AVR to 4\n");
		usleep(300 * 1000);
		pc(sc, sel4);
		active = 4;
		break;
	case 5:
		db("CHANGE AVR to 5\n");
		usleep(300 * 1000);
		pc(sc, sel5);
		active = 5;
		break;
	default:
		db("unknown tivo source for %d\n", avr);
		break;
	}
}

int
chomp(char *buf, int *hz, int *pairs)
{
	char *s, *p;
	int np;
	int dig1, dig0;
	int pairA, pairB, pairC, pairD;

	pairA = pairB = pairC = pairD = -1;
	np = 0;

	if (strncmp(buf, "GC-IRE,", 7) != 0)
		return (0);
	p = &buf[7];
	s = strsep(&p, ",");
	*hz = atoi(s);
	if (p == NULL)
		return (0);
	for (;;) {
		if (*p == '\0')
			break;
		if (*p == ',') {
			p++;
			continue;
		}
		if (*p == 'A') {
			pairs[np++] = pairs[pairA + 0];
			pairs[np++] = pairs[pairA + 1];
			p++;
			continue;
		}
		if (*p == 'B') {
			pairs[np++] = pairs[pairB + 0];
			pairs[np++] = pairs[pairB + 1];
			p++;
			continue;
		}
		if (*p == 'C') {
			pairs[np++] = pairs[pairC + 0];
			pairs[np++] = pairs[pairC + 1];
			p++;
			continue;
		}
		if (*p == 'D') {
			pairs[np++] = pairs[pairD + 0];
			pairs[np++] = pairs[pairD + 1];
			p++;
			continue;
		}
		dig1 = strtol(p, &p, 0);
		if (*p == ',') {
			p++;
		} else {
			return (0);
		}
		dig0 = strtol(p, &p, 0);
		if (pairA == -1)
			pairA = np;
		else if (pairB == -1)
			pairB = np;
		else if (pairC == -1)
			pairC = np;
		else if (pairD == -1)
			pairD = np;
		pairs[np++] = dig1;
		pairs[np++] = dig0;
	}
	return (np);
}

void
event(char *buf)
{
	int e;
	int n;
	int i;
	int l;
	int pairs[1024];
	int hz;
	int np;
	int rem, key;
	int gotsig[16];
	int matched;
	char lm[1024];
	char *plm;

	syslog(LOG_INFO, "event: %s", buf);
#if 1
	db("EVENT: %s\n", buf);
#endif
	l = 0;
	np = chomp(buf, &hz, pairs);
	if (np > 0) {
		sprintf(lm, "hz: %d, np %d, pairs:", hz, np);
		for (i = 0; i < (np - 1); i += 2) {
			plm = lm + strlen(lm);
			sprintf(plm, " %d,%d", pairs[i], pairs[i + 1]);
		}
		syslog(LOG_INFO, "%s", lm);
	}
	db("%s\n", lm);
	if (hz < 35000 || hz > 42000) {
		db("hz != 38000, not tivo\n");
		return;
	}
	if (np != 68) {
		db("np != 68, not tivo\n");
		return;
	}
	if (pairs[0] < 300 || pairs[0] > 370) {
		db("pairs[0] != 338, not tivo\n");
		return;
	}
	if (pairs[1] < 150 || pairs[1] > 180) {
		db("pairs[1] != 168, not tivo\n");
		return;
	}
	for (i = 0; i < 16; i++) {
		n = pairs[3 + 2 * i];
		if (n > 18 && n < 25)
			e = 0;
		else if (n > 57 && n < 65)
			e = 1;
		else {
			db("not tivo, index %d = %d\n", i, n);
			return;
		}
		gotsig[i] = e;
	}
	if (debug) {
		for (i = 0; i < 16; i++) {
			printf("%d,", gotsig[i]);
		}
		printf("\n");
	}


	/* Check Buffalo */
	matched = 1;
	for (i = 0; i < 16; i++) {
		if (gotsig[i] != vidsig[i]) {
			db("vidsig %d not matched %d\n", i, e);
			matched = 0;
		}
	}
	if (matched == 1) {
		if (active != 1)
			setavr(1);
		return;
	}

	/* Check tivos */
	matched = 1;
	for (i = 0; i < 16; i++) {
		if (gotsig[i] != tivosig[i]) {
			db("tivosig %d not matched %d\n", i, e);
			matched = 0;
		}
	}
	if (matched == 0) {
		return;
	}

		
	if (debug) {
		for (i = 7; i <= 65; i += 2) {
			if (pairs[i] > 40) 
				printf("1");
			else
				printf("0");
		}
		printf("\n");
	}
	rem = 0;
	if (pairs[51] > 40)
		rem |= 1;
	if (pairs[53] > 40)
		rem |= 2;
	if (pairs[55] > 40)
		rem |= 4;
	if (pairs[57] > 40)
		rem |= 8;
	db("REMOTE %d ", rem);

	key = 0;
	if (pairs[35] > 40)
		key |= 1;
	if (pairs[37] > 40)
		key |= 2;
	if (pairs[39] > 40)
		key |= 4;
	if (pairs[41] > 40)
		key |= 8;

	if (pairs[43] > 40)
		key |= 16;
	if (pairs[45] > 40)
		key |= 32;
	if (pairs[47] > 40)
		key |= 64;
#if 0
	if (pairs[49] > 40)
		db("[[XXX pair 49]]");
#endif
	if (pairs[59] > 40)
		key |= 128;
	if (pairs[61] > 40)
		key |= 256;
	if (pairs[63] > 40)
		key |= 512;
	syslog(LOG_INFO, "tivo %d key 0x%x", rem, key);
	db("key %03X\n", key);
	if (key == 0x31b)	/* vol mute */
		return;
	if (key == 0x31c)	/* vol up */
		return;
	if (key == 0x31d)	/* vol down */
		return;
	if (key == 0x1c4 /* window */ || key == 0x310 /* power */) {
		if (key == 0x310)
			sleep(1);
		if (rem == 2) {
			setavr(4);
		} else if (rem == 4) {
			setavr(5);
		} else {
			db("unknown tivo\n");
		}
	} else {
		if (rem == 2) {
			if (active != 4)
				setavr(4);
		} else if (rem == 4) {
			if (active != 5)
				setavr(5);
		} else {
			db("unknown tivo\n");
		}
	}

}

int
main(int ac, char *av[])
{
	struct sockaddr_in sin;
	int se;
	int e;
	int n;
	char buf[1024];
	char reply[1024];
	int l;
	int lr;
	struct hostent *hp;
	int pairs[1024];
	fd_set set;

	debug = 0;
	if (getenv("DEBUG"))
		debug = 1;

	openlog("autosource", LOG_NDELAY | LOG_PID, LOG_LOCAL1);
	hp = gethostbyname("gc100");
	if (hp == NULL)
		err(1, "gethostbyname: gc100: %s", hstrerror(h_errno));

reopen:
	bzero(&sin, sizeof(sin));
	bcopy(hp->h_addr, &sin.sin_addr, hp->h_length);
	sin.sin_family = AF_INET;
	sin.sin_len =  sizeof(sin);

	/* command socket */
	sin.sin_port = htons(4998);
	sc = socket(PF_INET, SOCK_STREAM, 0);
	if (sc == -1)
		err(1, "socket");

	e = connect(sc, (struct sockaddr *)&sin, sizeof(sin));
	if (e == -1)
		err(1, "command socket connect");


	/* IRE event socket */
	sin.sin_port = htons(4999);
	se = socket(PF_INET, SOCK_STREAM, 0);
	if (se == -1)
		err(1, "socket");

	e = connect(se, (struct sockaddr *)&sin, sizeof(sin));
	if (e == -1)
		err(1, "IRE event connect");

	l = 0;
	lr = 0;
	bzero(pairs, sizeof(pairs));

	for (;;) {
		FD_ZERO(&set);
		FD_SET(se, &set);
		FD_SET(sc, &set);
		n = select(32, &set, 0, 0, 0);
		if (n == -1) {
			if (errno == EINTR)
				continue;
			err(1, "select");
		}
		if (n == 0) {
			continue;
		}
		/* command socket */
		if (FD_ISSET(sc, &set)) {
			n = read(sc, &reply[lr], 1);
			if (n <= 0) {
				close(sc);
				close(se);
				sleep(1);
				goto reopen;
			}
			if (n != 1)
				continue;
			if (reply[lr] == '\r') {
				db("REPLY: %.*s\n", lr, reply);
				lr = 0;
				if (strncmp(reply, "completeir", 10) == 0) {
					if (sendwait) {
						db("SENDING WAITING CMD: %s\n", cmd);
						write(sc, cmd, strlen(cmd));
						sendwait = 0;
					} else {
						sendbusy = 0;
					}

				}
			} else {
				lr++;
			}
		}
		if (FD_ISSET(se, &set)) {
			n = read(se, &buf[l], 1);
			if (n <= 0) {
				close(sc);
				close(se);
				sleep(1);
				goto reopen;
			}
			if (buf[l] != '\0') {
				l++;
				continue;
			}
			event(buf);
			l = 0;
		}
	}
	exit(0);
}
