#!/bin/bash
# Verify a valid zlib-compressed Lumberjack window is decoded, submitted, and
# acknowledged with the final sequence number.
. ${srcdir:=.}/diag.sh init

generate_conf
add_conf '
module(load="../plugins/imbeats/.libs/imbeats")

template(name="outfmt" type="string"
         string="%msg%|%$!message%|%$!metadata!imbeats!sequence%\n")

ruleset(name="main") {
  action(type="omfile" file="'$RSYSLOG_OUT_LOG'" template="outfmt")
}

input(type="imbeats"
      port="0"
      listenPortFileName="'$RSYSLOG_DYNNAME'.imbeats.port"
      ruleset="main")
'

startup
assign_rs_port "$RSYSLOG_DYNNAME.imbeats.port"

python3 - "$RS_PORT" > "$RSYSLOG_DYNNAME.imbeats.ack" <<'PY'
import json
import socket
import struct
import sys
import zlib

port = int(sys.argv[1])
payload = json.dumps({"message": "compressed"}, separators=(",", ":")).encode()
nested = b"2J" + struct.pack(">I", 1) + struct.pack(">I", len(payload)) + payload
compressed = zlib.compress(nested)
wire = b"2W" + struct.pack(">I", 1) + b"2C" + struct.pack(">I", len(compressed)) + compressed

sock = socket.create_connection(("127.0.0.1", port))
sock.sendall(wire)
ack = sock.recv(6)
sys.stdout.write(ack.hex())
sock.close()
PY

shutdown_when_empty
wait_shutdown

# shellcheck disable=SC2034
EXPECTED='{"message":"compressed"}|compressed|1'
cmp_exact

test "$(cat "$RSYSLOG_DYNNAME.imbeats.ack")" = "324100000001"

exit_test
