#!/usr/bin/lua

local wireless = require 'gluon.wireless'

local uci = require('simple-uci').cursor()


local function is_disabled(config, name)
	if uci:get('wireless', name) then
		return uci:get_bool('wireless', name, 'disabled')
	end

	return config.disabled(false)
end

local function configure_ap(radio, index, config, radio_name)
	local name = 'client_' .. radio_name
	local suffix = radio_name:match('^radio(%d+)$')

	local ap = config.ap
	local disabled = is_disabled(ap, name)

	uci:delete('wireless', name)

	local macaddr = wireless.get_wlan_mac(uci, radio, index, 1)

	if not ap.ssid() or not macaddr then
		return
	end

	uci:section('wireless', 'wifi-iface', name, {
		device = radio_name,
		network = 'client',
		mode = 'ap',
		ssid = ap.ssid(),
		macaddr = macaddr,
		ifname = suffix and 'client' .. suffix,
		disabled = disabled or false,
	})
end

local function configure_owe(radio, index, config, radio_name)
	local name = 'owe_' .. radio_name
	local suffix = radio_name:match('^radio(%d+)$')

	local ap = config.ap

	local disabled = is_disabled(ap, 'client_' .. radio_name)

	uci:delete('wireless', name)

	-- Don't configure OWE in case our device
	-- can't do MFP, as it's mandatory for OWE.
	if not wireless.device_supports_mfp(uci) then
		return
	end

	local macaddr = wireless.get_wlan_mac(uci, radio, index, 3)

	if not ap.owe_ssid() or not macaddr then
		return
	end

	uci:section('wireless', 'wifi-iface', name, {
		device = radio_name,
		network = 'client',
		mode = 'ap',
		ssid = ap.owe_ssid(),
		macaddr = macaddr,
		ifname = suffix and 'owe' .. suffix,
		disabled = disabled or false,
		encryption = 'owe',
		ieee80211w = 2,
	})
end

local function configure_owe_transition_mode(config, radio_name)
	local ap = config.ap

	-- Don't configure OWE in case our device
	-- can't do MFP, as it's mandatory for OWE.
	if not wireless.device_supports_mfp(uci) then
		return
	end

	if not ap.owe_transition_mode(false) then
		return
	end

	local name_client = 'client_' .. radio_name
	local name_owe = 'owe_' .. radio_name

	local ifname_client = uci:get('wireless', name_client, 'ifname')
	local ifname_owe = uci:get('wireless', name_owe, 'ifname')

	if not (ifname_client and ifname_owe) then
		return
	end

	uci:set('wireless', name_client, 'owe_transition_ifname', ifname_owe)
	uci:set('wireless', name_owe, 'owe_transition_ifname', ifname_client)

	uci:set('wireless', name_owe, 'hidden', '1')
end

wireless.foreach_radio(uci, function(radio, index, config)
	local radio_name = radio['.name']

	configure_ap(radio, index, config, radio_name)

	configure_owe(radio, index, config, radio_name)
	configure_owe_transition_mode(config, radio_name)
end)

uci:save('wireless')
