#!/bin/bash
# bee-log-run — run a command, append its output to a file, and keep stdout/stderr
# connected to systemd so journald and the serial console also receive the logs.

set -o pipefail

log_file="$1"
shift

if [ -z "$log_file" ] || [ "$#" -eq 0 ]; then
    echo "usage: $0 <log-file> <command> [args...]" >&2
    exit 2
fi

mkdir -p "$(dirname "$log_file")"

serial_sink() {
    local tty="$1"
    if [ -w "$tty" ]; then
        cat > "$tty" 2>/dev/null || true
    else
        cat > /dev/null
    fi
}

"$@" 2>&1 | tee -a "$log_file" \
    >(serial_sink /dev/ttyS0) \
    >(serial_sink /dev/ttyS1)
exit "${PIPESTATUS[0]}"
