#!/bin/sh

# -------------------------------------------------------------------------- #
# Copyright 2002-2021, OpenNebula Project, OpenNebula Systems                #
#                                                                            #
# Licensed under the Apache License, Version 2.0 (the "License"); you may    #
# not use this file except in compliance with the License. You may obtain    #
# a copy of the License at                                                   #
#                                                                            #
# http://www.apache.org/licenses/LICENSE-2.0                                 #
#                                                                            #
# Unless required by applicable law or agreed to in writing, software        #
# distributed under the License is distributed on an "AS IS" BASIS,          #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   #
# See the License for the specific language governing permissions and        #
# limitations under the License.                                             #
# -------------------------------------------------------------------------- #

# As of Netplan 0.102, the NetworkManager renderer can only enable
# IPv6 privacy if ipv6-privacy == true, but doesn't disable it if false.
# Instead of enforcing any global defaults, we set IPv6 privacy via sysctl
# on Netplan described interfaces in case the current settings is -1 (unknown),
# i.e. not explicitly configured. This is a forward compatible workaround, once
# Netplan properly sets NM ipv6.ip6-privacy=0, this code won't be effective.

case "${CONNECTION_ID}" in
    netplan-*)
        IP6_PRIVACY=$(nmcli -g ipv6.ip6-privacy con show "${CONNECTION_UUID}")

        # overwrite only unknown state
        if [ "${IP6_PRIVACY}" = '-1' ]; then
            sysctl -q -w "net.ipv6.conf.${DEVICE_IFACE}.use_tempaddr=0"

            # delete any existing temporary IPv6 addresses
            ip -6 address show dev "${DEVICE_IFACE}" | \
                grep 'inet6.*temporary' | \
                tr -s ' ' | \
                cut -d' ' -f 3 | \
                xargs -r -n1 ip -6 address del dev "${DEVICE_IFACE}"
        fi
        ;;
esac

exit 0
