#!/usr/bin/env bash

# Thread network setup extracted from HandleFormNetworkRequest():
# https://github.com/openthread/ot-br-posix/blob/main/src/web/web-service/wpan_service.cpp#L100

set -eEuo pipefail

# When ot-ctl returns anything other than the string "Done" it failed
run_check_ot-ctl() {
  echo $1
  ot-ctl "$1" | grep -z "^Done[[:cntrl:]]*$"
}

ot-ctl factoryreset 2>/dev/null || true;
sleep 4;

eui64=$(cat /sys/class/net/eth0/address | sed -E -e 's/://g' -e 's/(.{6})/\1ffff/')
run_check_ot-ctl "extaddr $eui64"

run_check_ot-ctl "networkname somenetwork"
run_check_ot-ctl "extpanid dada1234affe5678"
run_check_ot-ctl "panid 0xdada"
run_check_ot-ctl "masterkey ffffffffffffffffffffffffffffffff"
run_check_ot-ctl "channel 23"
run_check_ot-ctl "pskc -p 123456"
run_check_ot-ctl "ifconfig up"
run_check_ot-ctl "thread start"

run_check_ot-ctl "prefix add fd01::/64 pasor"
run_check_ot-ctl "route add 64:ff9b::/96 s med"
run_check_ot-ctl "netdata register"

exit 0
