#!/bin/sh
#
# Copyright (C) 2018 devolo AG
#

. /usr/lib/lh-migration.sh

calc_netmask() {
    local ui32=$((0xffffffff << (32 - $1)))
    local ip n
    for n in 1 2 3 4; do
        ip=$((ui32 & 0xff))${ip:+.}$ip
        ui32=$((ui32 >> 8))
    done
    echo $ip
}

function migrate_lan_v4() {
    logger "Migrating LAN"
    local lh_path="$.SystemConfig.Services.Network.Management"
    local uci_path="network.lan"
    local NW_TYPE="$(lh_filter $lh_path.Type)"
    if [ "$NW_TYPE" = "DHCP" ]; then
        uci set $uci_path.proto='dhcp'
        uci delete $uci_path.ipaddr
        uci delete $uci_path.netmask
        uci delete $uci_path.gateway
        uci delete $uci_path.dns
    elif [ "$NW_TYPE" = "static" ]; then
        uci set $uci_path.proto='static'
        uci set $uci_path.ipaddr="$(lh_filter $lh_path.V4.IpAddress)"
        local PREFIX_LEN=$(lh_filter $lh_path.V4.PrefixLength)
        uci set $uci_path.netmask="$(calc_netmask $PREFIX_LEN)"
        uci set $uci_path.gateway="$(lh_filter $lh_path.V4.DefaultGateway.IpStatic)"
        uci set $uci_path.dns="$(lh_filter $lh_path.V4.Nameserver)"
    fi
}

function migrate_network() {
    logger "Migrating network"
    config_load network
    migrate_lan_v4
    uci_commit network
}

migrate_network
