#!/usr/bin/env lua

-- binary to hex
function h(s)
    local function hex(s)
        return string.format("%02x", string.byte(s))
    end
    return "["..#s.."] "..string.gsub(s, ".", hex)
end

local function debug(...)
    --print(...)
end

require"pcap"
require"net"
require"tostring"

cap = assert(pcap.open_offline(arg[1]))
n = net.init()

local i = 0;
for pkt, time, len in cap.next, cap do
    if pkt then
        i = i + 1
        print("packet", i, "wirelen", len, "timestamp", time, os.date("!%c", time))
        debug("snap", h(pkt))

        assert(n:clear())
        assert(n:decode_eth(pkt))

        local block = assert(n:block())
        if block ~= pkt then
            print("=> reencoding failed!")
	    local tag = n:tag_above()
	    while tag do
		print(n:pblock(tag))
		tag = n:tag_below(tag)
	    end
            print("pkt", h(pkt))
            print("out", h(block))
	    print("udp", n:get_udp())
	    print("eth", n:get_eth())
	    os.exit(1)
        end
    else
        print(pkt, time)
    end
end

