#!/bin/sh

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

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

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

uci commit ffberlin-uplink

. /lib/functions/guard.sh
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
# Create a static macaddr starting with "fe" for ffuplink devices
# See the website https://www.itwissen.info/MAC-Adresse-MAC-address.html
macaddr="fe"
for byte in 2 3 4 5 6; do
  macaddr=$macaddr`dd if=/dev/urandom bs=1 count=1 2> /dev/null | hexdump -e '1/1 ":%02x"'`
done
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 commit network.ffuplink
