#!/bin/sh
# Starts otbr-agent on the radio the host layer gave this backend.
#
# The backend's name arrives as $1, the %i of the unit. The radio arrives as
# OTBR_RCP_PORT, which phi-hostd writes into the backend's environment file when
# it is bound to one - a /dev/serial/by-id path, so it survives a reboot and a
# second stick. Nothing here names a device.
#
# OTBR_INFRA_IF from /etc/phi/otbr.env wins for the LAN side; otherwise the
# interface of the default route is it, which is right for a box with one uplink
# and wrong for nothing phi ships. OTBR_RCP_URL and OTBR_THREAD_IF can be set
# the same way, for the case somebody drives an RCP this layer cannot describe.
set -eu

. /usr/libexec/phi-otbr/interface.sh

instance=${1:-}
thread_if=$(thread_interface "$instance") || exit $?

rcp=${OTBR_RCP_URL:-}
if [ -z "$rcp" ]; then
    port=${OTBR_RCP_PORT:-}
    if [ -z "$port" ]; then
        echo "phi-otbr: backend $instance has no radio. The host layer writes the port when" \
             "the backend is bound to one:" \
             "phi-cli backend create --kind openthread --id $instance --resource <resource>" >&2
        # 78, which the unit will not restart after: a backend nobody bound to a
        # radio will not become bound by being started again. A radio that is
        # merely unplugged never reaches here - ExecStartPre waits for it.
        exit 78
    fi
    rcp="spinel+hdlc+uart://$port?uart-baudrate=${OTBR_RCP_BAUD:-115200}"
fi

infra=${OTBR_INFRA_IF:-}
if [ -z "$infra" ]; then
    infra=$(ip -o route show default 2>/dev/null | awk '{for (i = 1; i <= NF; i++) if ($i == "dev") {print $(i + 1); exit}}')
fi
if [ -z "$infra" ]; then
    infra=$(ip -o -6 route show default 2>/dev/null | awk '{for (i = 1; i <= NF; i++) if ($i == "dev") {print $(i + 1); exit}}')
fi
if [ -z "$infra" ]; then
    echo "phi-otbr: no default route and OTBR_INFRA_IF unset; no backbone" >&2
    exit 1
fi

echo "phi-otbr: backend $instance, backbone $infra, thread $thread_if, rcp $rcp"
# -s: standard error instead of syslog. Without it every line is in the journal
# twice - once from syslog under `otbr-agent` and once from the unit's own
# output - and only the second one comes back for `journalctl -u`. Measured on
# the first instance that ran.
exec /usr/sbin/otbr-agent -s -I "$thread_if" -B "$infra" -v "$rcp" "trel://$infra"
