#include <stdio.h>
#include <pcap.h>

#include "ars.h"

int main(int argc, char **argv)
{
	pcap_t *pcapfp;
	char errbuf[PCAP_ERRBUF_SIZE];
	struct pcap_pkthdr hdr;

	struct ars_iface i;
	struct ars_packet p;
	int s;

	ars_init(&p);

	s = ars_open_rawsocket(&p);
	if (s == -ARS_ERROR) {
		perror("Opening raw socket");
		exit(1);
	}

	if (ars_get_iface(argv[1], &i) != ARS_OK) {
		fprintf(stderr, "Can't get any good interface\n");
		exit(1);
	}

	pcapfp = pcap_open_live(i.if_name, ARS_MAX_IP_SIZE, 1, 0, errbuf);
	if (pcapfp == NULL) {
		fprintf(stderr, "Opening libpcap: %s\n", errbuf);
		exit(1);
	}

	while(1) {
		struct ars_packet pkt;
		unsigned char *p;
		int lhs, j;

		p = (unsigned char*) pcap_next(pcapfp, &hdr);
		if (p == NULL) {
			printf("pcap timeout\n");
			continue;
		}
		printf("Received %d bytes\n", hdr.caplen);
		if (ars_guess_ipoff(p, hdr.caplen, &lhs) != -ARS_OK) {
			printf("Can't guess lhs! (ARP?)\n");
			continue;
			exit(1);
		} else {
			printf("Link header size: %d\n", lhs);
		}
		ars_init(&pkt);
		ars_split_packet(p, hdr.caplen, -1, &pkt);
		printf("DUMP:\n");
		for (j = 0; j < ARS_MAX_LAYER; j++) {
			if (pkt.p_layer[j].l_type == ARS_TYPE_NULL)
				break;
		printf("layer %02d size %02d rel_size: %02d type: %s %s\n", j, pkt.p_layer[j].l_size, ars_relative_size(&pkt, j), ars_linfo[pkt.p_layer[j].l_type].li_name, pkt.p_layer[j].l_flags & ARS_SPLIT_FBADCKSUM ? "badcksum" : "");
		}
		ars_destroy(&pkt);
	}

	return 0;
}
