#!/bin/sh

. /lib/functions.sh
#this script move configuration from 1.x firmware
#it should rename some sections and add option disabled to network config

move_config() {
	local section="$1"
	local file="$2"

	config_get_bool enabled "$1" "enabled" "0"
	config_get _name "$1" "_name"
	config_get _type "$1" "_type"
	[ -z "$_type" ] && config_get _type "$1" "type"
	[ "$enabled" -eq 1 ] && [ "$_type" = "client" ] && {
		uci_set "network" "$1" "auto" "1"
		uci_commit "$config"
	}
	[ -n "$_name" ] && [ "$_name" != "$section" ] && {
		uci_rename "$file" "$section" "$_name"
		uci_commit "$config"
	}
}

move_network() {
	local section="$1"
	local net_proto net_name net_type net_enabled

	config_get net_proto "$section" "proto"

	case "$net_proto" in
		pptp|\
		l2tp)
			config_get net_name "$1" "_name"
			config_get_bool net_enabled "$1" "enabled"
			[ "client_${net_name}" = "$section" ] && return
			[ -n "$net_enabled" ] && {
				if [ "$net_enabled" = "1" ]; then
					uci_set "network" "$section" "disabled" "0"
				else
					uci_set "network" "$section" "disabled" "1"
				fi
				uci_remove "network" "$section" "enabled"
			}
			uci_rename "network" "$section" "${net_type:+${net_type}_}${net_name}"
			uci_commit "network"
			
			;;
		sstp)
			config_get_bool net_enabled "$1" "enabled"
			[ -z "$net_enabled" ] && return
			if [ "$net_enabled" = "1" ]; then
				uci_set "network" "$section" "disabled" "0"
			else
				uci_set "network" "$section" "disabled" "1"
			fi
			uci_remove "network" "$section" "enabled"
			uci_commit "network"
			;;
		*)
			return
			;;
	esac
}

# removes client configurations, because they reside in network and with vuci became unncessary
remove_network() {
	local section="$1"
	local current_config="$2"
	local sectionType
	config_get sectionType "$1" "type"
	if [ "$sectionType" = "client" ]; then
		uci_remove "$current_config" "$section"
		uci_commit "$current_config"
	fi
}

configs="pptpd xl2tpd"

for config in $configs; do
	[ -s "$UCI_CONFIG_DIR/${config}" ] || continue
	config_load "$config"
	config_foreach move_config "service" "$config"
	config_foreach remove_network "service" "$config"
done

[ -s "$UCI_CONFIG_DIR/network" ] || exit 0
config_load "network"
config_foreach move_network "interface"

exit 0
