/*
 * Don't panic // By kaner <kaner@strace.org>
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <string.h>
#include <linux/limits.h>
#include <netinet/in.h>
#include <arpa/inet.h>

const char progname[] = "beaconlogcrunch";
const char version[] = "0.1-alpha";

static void usage()
{
	printf("\nUsage: %s [OPTIONS]\n", progname);
	printf("\nOptions are:\n");
	printf("\t-f FILENAME: Use file FILENAME to parse\n");
	printf("\n");
	printf("%s Version %s\n", progname, version);
	printf("\n");
}

int main(int argc, char *argv[])
{
	FILE *logfile = NULL;
	char filename[PATH_MAX] = "./logall"; /* Default file name */
	struct in_addr logaddy;
	size_t count = 0;
	time_t stamp = 0;
	int npackets = 0;
	int nread = 0;
	int c = 0;
	u_int32_t ent = 0;

	while ((c = getopt(argc, argv, "f:")) != -1) {
		switch (c) {
			case 'f':
				if (!optarg) {
					fprintf(stderr, "No argument given for -f\n");
					exit(EXIT_FAILURE);
				}
				strncpy(filename, optarg, PATH_MAX-1);
				printf("filename: %s\n", filename);
				break;
			default:
				usage();
				exit(EXIT_FAILURE);
				break;
		}
	}

	if ((logfile = fopen(filename, "r")) == NULL) {
		perror("Couldn't open logfile. Please provide a correct logfile with -f.");
		exit(EXIT_FAILURE);
	}
	while (!feof(logfile)) {
		if ((count = fread(&ent, 1, sizeof(ent), logfile)) < sizeof(ent)) {
			fprintf(stderr, "Couldn't read from file.\n");
			exit(EXIT_FAILURE);
		}
		switch (nread) {
			case 0:
				stamp = ntohl(ent);
				break;
			case 1: /* Chunk #1 is the source IP address */
				logaddy.s_addr = ntohl(ent);
				printf("%s\t", inet_ntoa(logaddy));
				break;
			case 3: /* Chunk #3 is source IP reverted [Thanks, Peter Meerwald] */
				logaddy.s_addr = ent; /* !!! */
				printf("%s\t", inet_ntoa(logaddy));
				break;
			case 5: /* Chunk #5 is the OID */
				printf("%d\t", ntohl(ent));
				break;
			default:
				printf("%x\t", ntohl(ent));
				break;
		}
		if (++nread >= 6) {
			printf("- Packet %d, %d bytes, %s", npackets++, nread*(sizeof(ent)), ctime(&stamp));
			nread = 0;
		}
	}
	if (fclose(logfile) == EOF) {
		perror("Couldn't close logfile");
		exit(EXIT_FAILURE);
	}
	
	exit(EXIT_SUCCESS);
}
