#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pcap.h>
#include <err.h>
#include <string.h>
#include <time.h>

int
main(int argc, char *argv[])
{
    pcap_t *in = NULL;
    pcap_dumper_t *out = NULL;
    char errbuf[PCAP_ERRBUF_SIZE + 1];
    struct pcap_pkthdr hdr;
    time_t this_bin;
    time_t last_bin = -1;
    time_t modulus = 300;
    const u_char *data;
    char *fmt;

    if (3 != argc) {
	fprintf(stderr, "usage: tcpdump-split seconds strftime\n");
	exit(1);
    }
    modulus = (time_t) atoi(argv[1]);
    fmt = strdup(argv[2]);

    in = pcap_open_offline("-", errbuf);
    if (NULL == in) {
	fprintf(stderr, "stdin: %s", errbuf);
	exit(1);
    }
    while ((data = pcap_next(in, &hdr))) {
	this_bin = hdr.ts.tv_sec - (hdr.ts.tv_sec % modulus);
	if (this_bin != last_bin) {
	    char fname[128];
	    if (out)
		pcap_dump_close(out);
	    strftime(fname, 128, fmt, gmtime(&this_bin));
	    out = pcap_dump_open(in, fname);
	    if (NULL == out) {
		perror(fname);
		exit(1);
	    }
	    last_bin = this_bin;
	}
	pcap_dump((void *)out, &hdr, data);
    }
    if (out)
	pcap_dump_close(out);
    exit(0);
}
