#!/usr/bin/bash
#
# collect messages from reporter and drop them into log files
#
set -eu

port=1234
#logdir="/var/log/collector"
logdir="/tmp/collector"

mkdir -vp "$logdir"

nc -k -l -u -p "$port" | while read line ; do
    sndr="${line%% *}"
    msg="${line#* }"
    if [[ "$sndr" =~ [a-z0-9]+ ]] ; then
        if [[ "$msg" =~ ^-------\ .+\ -------$ ]] ; then
            echo "$(date --rfc-3339=seconds) → Report from '$sndr' received."
            echo "$msg" >  "$logdir/$sndr"
        else
            echo "$msg" >> "$logdir/$sndr"
        fi
    fi
done
