#!/bin/sh /etc/rc.common

SETUP_MODE_ADDR=192.168.1.1
SETUP_MODE_NETMASK=255.255.255.0

START=20
STOP=90

USE_PROCD=1


delete_interface() {
	[ "$1" = 'loopback' ] || uci_remove network "$1"
}

prepare_config() {
(
	export UCI_CONFIG_DIR=/var/gluon/setup-mode/config

	mkdir -p "$UCI_CONFIG_DIR"

	cp /etc/config/network "$UCI_CONFIG_DIR"

	config_load network
	config_foreach delete_interface interface

	uci_add network interface setup
	uci_set network setup ifname "$(lua -e 'print(require("gluon.sysconfig").setup_ifname)')"
	uci_set network setup macaddr "$(lua -e 'print(require("gluon.sysconfig").primary_mac)')"
	uci_set network setup type 'bridge'
	uci_set network setup proto 'static'
	uci_set network setup ipaddr "$SETUP_MODE_ADDR"
	uci_set network setup netmask "$SETUP_MODE_NETMASK"

	uci_commit network
)
}

init_switch() {
	setup_switch() { return 0; }

	include /lib/network
	setup_switch
}

start_service() {
	prepare_config
	init_switch
	iw reg set "$(lua -e 'print(require("gluon.site").regdom())')"

	procd_open_instance
	procd_set_param command /sbin/netifd -c /var/gluon/setup-mode/config
	procd_set_param respawn
	procd_set_param watch network.interface
	[ -e /proc/sys/kernel/core_pattern ] && {
		procd_set_param limits core="unlimited"
		echo '/tmp/%e.%p.%s.%t.core' > /proc/sys/kernel/core_pattern
	}
	procd_close_instance
}

reload_service() {
	init_switch
	ubus call network reload
	/sbin/wifi reload_legacy
}

stop_service() {
	/sbin/wifi down
}

service_running() {
	ubus -t 30 wait_for network.interface
	/sbin/wifi reload_legacy
}

restart() {
	ifdown -a
	sleep 1
	trap '' TERM
	stop "$@"
	start "$@"
}

shutdown() {
	ifdown -a
	stop
}
