#!/bin/bash

# To set a common prefix for all messages, do `export MSGTOPIC_PREFIX=...` in callers.
if [ -n "$MSGTOPIC_PREFIX" -a "${MSGTOPIC_PREFIX%.}" = "$MSGTOPIC_PREFIX" ]; then
    MSGTOPIC_PREFIX="${MSGTOPIC_PREFIX}."
fi
topic="${MSGTOPIC_PREFIX}$1"
shift
sent_at="$(TZ=UTC date -Iseconds)"
id="$(uuidgen -r)"
body="{"
sep=""

# To preset items in the message body, do `export MSGBODY_PRESET="key1=value1 key2=value2"` before
# calling simple_message_to_bus. This doesn't work with spaces in the keys or values, sorry.
for body_piece in $MSGBODY_PRESET "$@"; do
    key_type="${body_piece%%=*}"
    key="${key_type%%:*}"
    type="${key_type#${key}}"
    type="${type#:}"
    value="${body_piece#*=}"

    if [ "$type" != "int" ]; then
        # quote strings
        value="${value//\\/\\\\}"
        value="${value//\"/\\\"}"
        value="\"${value}\""
    fi
    body="${body}${sep}\"${key}\": ${value}"
    sep=", "
done
body="${body}}"

fedora-messaging publish - << EOF >/dev/null
{"body": ${body}, "headers": {"fedora_messaging_schema": "base.message", "fedora_messaging_severity": 20, "sent-at": "${sent_at}"}, "id": "${id}", "queue": "queue", "topic": "${topic}"}
EOF
