#!/bin/sh

. /lib/functions.sh

UCI_CONFIG_DIR="${UCI_CONFIG_DIR:-/etc/config}"
[ -f "$UCI_CONFIG_DIR/ipsec" ] || exit 0
[ -f "$UCI_CONFIG_DIR/network" ] || exit 0
[ -f "$UCI_CONFIG_DIR/firewall" ] || exit 0

migrate_routes() {
    local route=$1
    local interface proto device
    config_get interface "$route" interface
    config_get proto "$interface" proto
    [ "$proto" = "xfrm" ] || return
    config_get device "${interface}_static" device
    [ "$device" = "@$interface" ] && uci_set network "$route" interface "${interface}_static"
}

migrate_zones() {
    local zone=$1
    local network interface
    config_get network "$zone" network

    local new_network=""
    local changed=0
    for interface in $network; do
        if [ "$(uci_get network "$interface" proto)" = "xfrm" ]; then
            local device=$(uci_get network "${interface}_static" device)
            if [ "$device" = "@$interface" ]; then
                new_network="$new_network ${interface}_static"
                changed=1
            else
                new_network="$new_network $interface"
            fi
        else
            new_network="$new_network $interface"
        fi
    done

    [ "$changed" = "1" ] && uci_set firewall "$zone" network "${new_network# }"

}

config_load network
config_foreach migrate_routes route
config_load firewall
config_foreach migrate_zones zone

uci_commit network
uci_commit firewall

exit 0
