#!/bin/sh
# Brings one backend's Thread network up once its agent answers.
#
# The first start forms a network: a fresh dataset with random credentials,
# named "phi", committed as the active one. otbr-agent keeps it in its settings -
# a file named after the radio's own EUI-64, so it belongs to the stick rather
# than to this box - and on later starts attaches to it by itself. This script's
# second job is only the odd case where the dataset exists and Thread was left
# disabled. Idempotent; runs as ExecStartPost.
set -eu

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

instance=${1:-}
thread_if=$(thread_interface "$instance")
ctl="/usr/sbin/ot-ctl -I $thread_if"

for i in $(seq 1 60); do
    if $ctl state >/dev/null 2>&1; then
        break
    fi
    sleep 1
done
$ctl state >/dev/null 2>&1 || { echo "phi-otbr: agent not answering on $thread_if" >&2; exit 1; }

# The console socket is root's. phi's adapters (user phi) read the network
# and its dataset through it, so the phi group gets to write to it; a box
# without that group keeps the socket as it is.
sock="/run/openthread-$thread_if.sock"
group=${OTBR_CONSOLE_GROUP:-phi}
if [ -S "$sock" ] && getent group "$group" >/dev/null 2>&1; then
    chgrp "$group" "$sock" && chmod 0660 "$sock"
fi

dataset=$($ctl dataset active -x 2>/dev/null | head -n 1 | tr -d '\r')
case "$dataset" in
    ""|Error*|*"Not Found"*)
        echo "phi-otbr: no active dataset, forming a network"
        $ctl dataset init new >/dev/null
        $ctl dataset networkname "${OTBR_NETWORK_NAME:-phi}" >/dev/null
        $ctl dataset commit active >/dev/null
        ;;
esac

state=$($ctl state | head -n 1 | tr -d '\r')
if [ "$state" = "disabled" ]; then
    $ctl ifconfig up >/dev/null
    $ctl thread start >/dev/null
fi
echo "phi-otbr: backend $instance, state $($ctl state | head -n 1 | tr -d '\r'), network $($ctl networkname | head -n 1 | tr -d '\r')"
