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

START=12


CONFIG_MODE_ADDR=192.168.1.1
CONFIG_MODE_NETMASK=255.255.255.0

CONFIG_MODE_DHCP_RANGE=192.168.1.2,192.168.1.254


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


check_enable() {
	config_get enabled "$1" enabled
	config_get configured "$1" configured

	if [ "$enabled" = 1 -o "$configured" != 1 ]; then
		export enable=1
	fi
}

setup_network() {
	(
		export UCI_CONFIG_DIR=/var/gluon/config-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 config
		uci_set network config ifname "$(sysconfig config_ifname)"
		uci_set network config type 'bridge'
		uci_set network config proto 'static'
		uci_set network config ipaddr "$CONFIG_MODE_ADDR"
		uci_set network config netmask "$CONFIG_MODE_NETMASK"

		uci_commit network

		SERVICE_DAEMONIZE=1
		SERVICE_WRITE_PID=1
		service_start /sbin/netifd -c "$UCI_CONFIG_DIR"

		setup_switch() { return 0; }

		include /lib/network
		setup_switch
	)
}

start() {
	. /lib/gluon/functions/sysconfig.sh

	enable=0
	config_load gluon-config-mode
	config_foreach check_enable wizard

	if [ "$enable" = '1' ]; then
		lua -luci -e 'require "luci.model.uci"; uci_state=luci.model.uci.cursor_state(); uci_state:section("gluon-config-mode", "wizard", nil, { running = "1" }); uci_state:save("gluon-config-mode")'
		uci set 'gluon-config-mode.@wizard[0].enabled=0'
		uci commit gluon-config-mode

		setup_network

		/usr/sbin/telnetd -l /lib/gluon/config-mode/ash-login
		/etc/init.d/dropbear start

		/usr/sbin/uhttpd -h /lib/gluon/config-mode/www -x /cgi-bin -A 1 -R -p 0.0.0.0:80

		/usr/sbin/dnsmasq -p 0 -F $CONFIG_MODE_DHCP_RANGE -l /tmp/dhcp.leases -O option:router

		/etc/init.d/led start

		# correctly finish firstboot
		/etc/init.d/done boot

		. /etc/diag.sh
		get_status_led
		status_led_set_timer 1000 300

		# block further boot
		while true; do sleep 1; done
	fi
}