#!/bin/sh
# >>> CICADATAK B-17 (this block and the one below are the ONLY changes to the stock file)
# SPDX-License-Identifier: GPL-2.0-only
#
# Modified by CicadaTAK (2026-10-10) from batman-adv's netifd proto, /lib/netifd/proto/batadv_hardif.sh in the
# OpenWrt routing feed's kmod-batman-adv package (md5 96f498ae88932e4fc1a8baaaf4b39d63 in both the vanilla
# 2024.3-r11 and the classic 2025.4-r2 builds). This copy REPLACES the package's at image build time.
#
# The one change: before a radio joins bat0, /lib/cicadatak/bat-primary.sh makes sure a virtual interface,
# primary0, is already in bat0 and up, so it — not the radio — is batman's primary interface, and losing or
# reconfiguring a radio can never rename this node in the mesh (B-17: a renamed node stays unreachable for
# ~200 s; docs/batman-adv.md §Stable primary). The helper never blocks and never fails this setup.
#
# DRIFT GATE: pi-gateway/tests/test_batadv_hardif_shadow.py rebuilds the stock file from this one (by removing
# both marked blocks) and compares it byte-for-byte with the copy inside the committed kmod-batman-adv ipk, and
# pins that copy's md5. A package bump that changes the stock file fails it — re-derive this file then.
# <<< CICADATAK

[ -n "$INCLUDE_ONLY" ] || {
	. /lib/functions.sh
	. ../netifd-proto.sh
	init_proto "$@"
}

proto_batadv_hardif_init_config() {
	proto_config_add_int 'elp_interval'
	proto_config_add_int 'hop_penalty'
	proto_config_add_string "master"
	proto_config_add_string 'throughput_override'
}

proto_batadv_hardif_setup() {
	local config="$1"
	local iface="$2"

	local elp_interval
	local hop_penalty
	local master
	local throughput_override

	json_get_vars elp_interval
	json_get_vars hop_penalty
	json_get_vars master
	json_get_vars throughput_override

	( proto_add_host_dependency "$config" '' "$master" )

	# >>> CICADATAK B-17: primary0 first, so no radio is ever bat0's primary (/lib/cicadatak/bat-primary.sh).
	[ -r /lib/cicadatak/bat-primary.sh ] && . /lib/cicadatak/bat-primary.sh && bat_primary_ensure "$master"
	# <<< CICADATAK
	batctl meshif "$master" interface -M add "$iface"

	[ -n "$elp_interval" ] && batctl hardif "$iface" elp_interval "$elp_interval"
	[ -n "$hop_penalty" ] && batctl hardif "$iface" hop_penalty "$hop_penalty"
	[ -n "$throughput_override" ] && batctl hardif "$iface" throughput_override "$throughput_override"

	proto_init_update "$iface" 1
	proto_send_update "$config"
}

proto_batadv_hardif_teardown() {
	local config="$1"
	local iface="$2"

	local master

	json_get_vars master

	batctl meshif "$master" interface -M del "$iface" || true
}

add_protocol batadv_hardif
