#!/bin/sh

THIS_UPLINKNAME="notunnel"

. /lib/functions/freifunk-berlin-network.sh
. /lib/functions/guard.sh
. /lib/functions.sh

# always set correct masquerading, regardless of guard
uci set firewall.zone_ffuplink.masq=1
uci commit firewall

current_preset=$(uci get ffberlin-uplink.preset.current)
if [ ${current_preset} != ${THIS_UPLINKNAME} ]; then
    # do not track preset when it was 'undefined', aka never configured
    if [ ${current_preset} != "undefined" ]; then
        logger -t "ffuplink" "uplink-preset has been changed."
        uci set ffberlin-uplink.preset.previous=${current_preset}
        create_ffuplink
    fi
    uci set ffberlin-uplink.preset.current=${THIS_UPLINKNAME}
fi
# set set auth-type required for this uplink-type, e.g. for freifunk-wizard
uci set ffberlin-uplink.uplink.auth=none

# disable tunneldigger for ffuplink, if tunneldigger was the previous setup
if [ ${current_preset} == "tunnelberlin_tunneldigger" ]; then
    uci set tunneldigger.ffuplink.enabled=0
    uci commit tunneldigger
fi

macaddr=$(uci -q get ffberlin-uplink.uplink.macaddr)
if [ -z "$macaddr" ]; then
    macaddr=$(generate_random_mac_hex "fe")
    uci set ffberlin-uplink.uplink.macaddr=$macaddr
fi

uci commit ffberlin-uplink

guard "notunnel"

uci -q delete network.ffuplink_dev
uci set network.ffuplink_dev=device
uci set network.ffuplink_dev.type=veth
uci set network.ffuplink_dev.name=ffuplink
uci set network.ffuplink_dev.peer_name=ffuplink_wan
uci set network.ffuplink_dev.macaddr=$macaddr
uci commit network.ffuplink_dev

# add ffuplink_dev to the br-wan bridge if not there
handle_wan_device() {
    local config=$1
    local name=""
    local _ports=""
    local wandev

    wandev="$(uci -q get network.wan.device)"
    if [ -z $wandev ]; then
        return
    fi

    config_get name $config name
    if [ "X${name}X" == "Xbr-wanX" ]; then
        config_get _ports $config _ports
        list_contains _ports ffuplink_wan || uci add_list network.${config}.ports="ffuplink_wan"
        uci commit network.${config}
    fi
}

reset_cb
config_load network
config_foreach handle_wan_device device

uci set network.ffuplink.proto=dhcp
uci set network.ffuplink.hostname="freifunk-$(echo $macaddr | tr -d :)-uplink"
uci commit network.ffuplink
