#!/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 br-wan if not there
ifnames=$(uci get network.wan.ifname)
list_contains ifnames ffuplink_wan || uci set network.wan.ifname="${ifnames} ffuplink_wan"
uci commit network.wan

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