/*
 *   journal - locally read the phone call log on f!box fon et al.
 *   This is a very q'n'd hack.
 *
 *   Copyright (C) 2004  Enrik Berkhan <Enrik.Berkhan@inka.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
 */

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>

#include <errno.h>
#include <signal.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>

char query[] =
"<message><to>telcfg</to><from>webcm0</from><sequence>8</sequence><transaction><type>query</type><key>settings/Journal/list(Type,Route,Date,Number,Port,Duration)</key><error>0</error></transaction></message>";

char buf[1024];
int buflen = sizeof(buf) - 1;

void
parse_row(char **buf)
{
	char *val, *valend;

	while ((val = strstr(*buf, "<value>"))) {
		val += strlen("<value>");
		valend = strstr(val, "</value>");
		if (valend)
		  *valend = 0;
		printf("%s ", val);
		if (valend)
		  *buf = valend + strlen("</value>");
		else
		  *buf = val += strlen("<value>");
	}
}

void
parse_buf(char *buf)
{
	char *row = buf;

	while ((row = strstr(row, "<row>"))) {
		row += strlen("<row>");
		parse_row(&row);
	}
	puts("");
	return;
}

void
cleanup(void) {
	unlink("/var/tmp/cm_webcm0.ctl");
	return;
}

void
timeout(int signal) {
	return;
}

int
main(int argc, char *argv[])
{
	int sk;
	struct sockaddr_un addr;
	struct sigaction handler = {
		.sa_handler = timeout,
		.sa_mask = 0,
		.sa_flags = 0
	};

	if (-1 == (sk = socket(PF_LOCAL, SOCK_DGRAM, 0))) {
		perror("socket");
		return 1;
	}
	addr.sun_family = AF_UNIX;
	strcpy(addr.sun_path, "/var/tmp/cm_webcm0.ctl");
	unlink("/var/tmp/cm_webcm0.ctl");
	if (-1 == bind(sk, (struct sockaddr *)&addr, sizeof(addr))) {
		perror("bind");
		return 1;
	}
	atexit(cleanup);
	strcpy(addr.sun_path, "/var/tmp/cm_logic.ctl");
	if (-1 == sendto(sk, query, strlen(query), 0,
		         (struct sockaddr *)&addr, sizeof(addr))) {
		perror("sendto");
		return 1;
	}
	if (-1 == sigaction(SIGALRM, &handler, 0)) {
		perror("sigaction");
		return 1;
	}
	while(1) {
		int len, addrlen = sizeof(addr);
		alarm(1);
		if (0 > (len = recvfrom(sk, buf, buflen, 0,
		                 (struct sockaddr *)&addr, &addrlen))) {
			if (errno == EINTR) break;
			perror("recvfrom");
			return 1;
		}
		alarm(0);
		buf[len]=0;
		parse_buf(buf);
	}
	return 0;
}

