#!/bin/sh
# /usr/sbin/netmode-restore.sh

. /lib/functions.sh

LOG_TAG="netmode-restore"

log() {
	logger -t "$LOG_TAG" "$*"
	echo "[${LOG_TAG}] $*"
}

log "Starting netmode restore"

delete_extra_dhcp_sections() {
	log "Cleaning up dhcp UCI"

	# by default only lan and wan dhcp sections are present,
	# so delete any extra sections
	delete_dhcp_sec() {
		sec="$1"
		intf="$(uci -q get dhcp.$sec.interface)"
		if [ "$intf" != "wan" ] && [ "$intf" != "lan" ]; then
			log "deleting dhcp section $sec"
			uci -q delete dhcp.$sec
		fi
	}

	config_load "dhcp"
        config_foreach delete_dhcp_sec dhcp

	uci commit dhcp
}

restore_firewall() {
	log "Cleaning up firewall UCI"

	# in some netmodes, an extra mgmt zone is added
	# so we remove its zone and rules
	# ---- 1. reset wan zone networks -------------------------------------
	uci -q set firewall.wan.network=""

	# ---- 2. add base wan/wan6 -------------------------------------------
	for net in wan wan6; do
		uci -q add_list firewall.wan.network="$net"
	done

	delete_mgmt_rule() {
		sec="$1"
		src="$(uci -q get firewall.$sec.src)"
		dest="$(uci -q get firewall.$sec.dest)"
		if [ "$src" = "mgmt" ] || [ "$dest" = "mgmt" ]; then
			log "deleting firewall section $sec"
			uci -q delete firewall.$sec
		fi
	}

	# ---- 3. delete mgmt rules ---------------------------------------------
	config_load "firewall"
        config_foreach delete_mgmt_rule rule

	# ---- 4. delete mgmt zone ---------------------------------------------
	uci -q delete firewall.mgmt

	uci commit firewall
}

restore_services() {
	# Update CWMP Agent WAN Interface
	uci -q set cwmp.cpe.default_wan_interface="wan"
	uci -q commit cwmp

	# Update gateway WAN Interface
	uci -q set gateway.global.wan_interface="wan"
	uci -q commit gateway

	# Restore SSDPD
	cp /rom/etc/config/ssdpd /etc/config/ssdpd

	log "Service configurations restored"
}

log "Removing mtu configurations from network UCI"
sed -i '/mtu/d' /etc/config/network

restore_firewall
restore_services
delete_extra_dhcp_sections

log "Netmode restore completed"
exit 0
