#!/usr/bin/env lua5.1

require "pcap"
require "netutil"

local function gc()
    for _=1,5 do
        collectgarbage()
    end
end

function assertfail(...)
    --print("assertfail", ...)
    local ok, emsg = pcall(...)
    --print("pcall", ok, emsg)
    assert(ok == false, tostring(ok)..","..tostring(emsg))
    assert(emsg)
    return emsg
end

function assertnext(cap, _pkt, _stamp, _wirelen)
    local pkt, stamp, wirelen = cap:next()

    print("want", _pkt and h(_pkt) or "nil", _stamp, _wirelen)
    print("next", pkt and h(pkt) or "nil", stamp, wirelen)

    if _pkt then assert(_pkt == pkt) end
    if _stamp then assert(_stamp == stamp) end
    if _wirelen then assert(_wirelen == wirelen) end
end


assert(pcap)

print"test: tv to secs conversions"

for _, tvsecs in ipairs{0, 1, 2, 3, 4, 5, 100, 788964454} do
    for tvusecs=0,1000 do
        local secs = pcap.tv2secs(tvsecs, tvusecs)
        local _tvsecs, _tvusecs = pcap.secs2tv(secs)
        if tvusecs ~= _tvusecs or tvsecs ~= _tvsecs then
            if tvsecs == 0 then
                print("tv in", tvsecs, tvusecs, "secs", string.format("%.8f", secs), "tv out", _tvsecs, _tvusecs)
            end
        end
        assert(tvsecs == _tvsecs)
        assert(tvusecs == _tvusecs, "diff is "..(tvusecs - _tvusecs))
    end
end

print"+ok"

print"pcap test"

print("pcap lib version", assert(pcap._LIB_VERSION))

cap = assert(pcap.open_dead())
dmp = assert(cap:dump_open("cap0.pcap"))

eth = b"112233445566aabbccddeeff080045" -- eth header + 1 byte of ipv4

assert(dmp:dump(eth, 1.000010, #eth - 1 + 20))
assert(dmp:dump(eth, 2.000020))
assert(dmp:dump(eth))

assertfail(dmp.dump, dmp)
assertfail(dmp.dump, dmp, nil)

_, emsg = dmp:dump(nil, "msg")

assert(_ == nil)
assert(emsg == "msg")

cap:close()

assert(dmp:dump("pcap closed"))

dmp:close()

cap = assert(pcap.open_offline("cap0.pcap"))

assertnext(cap, eth, 1.000010, #eth - 1 + 20)
assertnext(cap, eth, 2.000020, #eth)
assertnext(cap, eth, nil, #eth)
assertnext(cap, "pcap closed", nil, #"pcap closed")
assertnext(cap, nil, nil, nil)

print"dlt table test"

assert(pcap.DLT)
assert(pcap.DLT.EN10MB == 1)
assert(pcap.DLT.LINUX_SLL == 113)
assert(pcap.DLT[1] == "EN10MB")
assert(pcap.DLT[113] == "LINUX_SLL")

print"+ok"


