#!/usr/bin/env bash

# -------------------------------------------------------------------------- #
# 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.                                             #
#--------------------------------------------------------------------------- #

#
# network module implementation
#

is_network_supported()
{
    command -v netplan >/dev/null

    return $?
}

configure_network()
{
    gen_resolvconf
    gen_network_configuration > /etc/netplan/00-opennebula-generated-network.yaml
    netplan generate
}

stop_network()
{
    service networking stop
}

start_network()
{
    service networking start
    netplan generate
    netplan apply
}

reload_network()
{
    netplan generate
    netplan apply
}

#
# helper functions
#

# TODO: remove global variables and get rid off exports
#
# to satisfy shellcheck SC2154:
export os_id
export ip
export network
export mask
export cidr
export ip6
export ip6_prefix_length
export ip6_ula
export mac
export dev
export mtu
export gateway
export gateway6
export method
export method6
export metric
export dns
export search_domains
export external
export detach
export all_nameservers
export all_search_domains

gen_addresses()
{
    case "${method}" in
        ''|static)
            [ -n "${ip}" ] && gen_addr_conf
            ;;
    esac

    case "${method6}" in
        ''|static)
            [ -n "${ip6}" ] && gen_addr6_conf
            ;;
    esac

    _aliases=$(get_interface_alias "$_iface")

    for _nic_alias in $_aliases; do
        setup_ipadr_vars "$_nic_alias"
        setup_ip6adr_vars "$_nic_alias"
        setup_alias_vars "$_nic_alias"

        if [ -z "${detach}" ]; then
            if ! is_true "${external}" ; then
                [ -n "${ip}"  ] && gen_addr_conf
                [ -n "${ip6}" ] && gen_addr6_conf
            fi
        fi
    done
}

gen_routes()
{
    if [ -n "${gateway}" ] ; then
        cat <<EOT
        - to: "0.0.0.0/0"
          via: ${gateway}
EOT

        if [ -n "${metric}" ] ; then
            echo "          metric: ${metric}"
        fi
    fi

    if [ -n "${gateway6}" ] ; then
        cat <<EOT
        - to: "::/0"
          via: ${gateway6}
EOT

        if [ -n "${metric}" ] ; then
            echo "          metric: ${metric}"
        fi
    fi
}

gen_dhcp_conf()
{
    cat <<EOT
      dhcp4: true
EOT
}

gen_addr_conf()
{
    echo "        - ${ip}/${cidr}"
}

gen_addr6_conf()
{
    echo "        - ${ip6}/${ip6_prefix_length:-64}"

    if [ -n "$ip6_ula" ]; then
        echo "        - ${ip6_ula}/64"
    fi
}

gen_dhcp6_conf()
{
    # TODO: is this really correct?
    if [ "${method6}" = "auto" ] ; then
        cat <<EOT
      accept-ra: true
      dhcp6: false
EOT
    else
        cat <<EOT
      accept-ra: true
      dhcp6: true
EOT
    fi
}

gen_ipv6_disable()
{
    # TODO: is this really correct? Won't it affect also IPv4 link-local?
    cat <<EOT
      accept-ra: false
      link-local: []
EOT
}

init_netplan_renderer()
{
    if [ -z "${NETCFG_NETPLAN_RENDERER}" ] ; then
        if command -v networkctl >/dev/null ; then
            NETCFG_NETPLAN_RENDERER='networkd'
        elif command -v nmcli >/dev/null ; then
            NETCFG_NETPLAN_RENDERER='NetworkManager'
        fi
    fi
}

gen_network_configuration()
{
    init_netplan_renderer

    # TODO: consider to change the default to more robust NetworkManager - the
    # netplan's renderer default is networkd which may encounter issues with
    # version 248
    cat <<EOT
network:
  version: 2
  renderer: ${NETCFG_NETPLAN_RENDERER:-networkd}
EOT

    # ethernets key must have at least one interface
    _ethernets_written=

    _context_interfaces=$(get_context_interfaces)

    for _iface in $_context_interfaces; do
        setup_iface_vars "$_iface"

        skip_interface && continue

        if [ -z "${_ethernets_written}" ] ; then
            echo "  ethernets:"
            _ethernets_written=yes
        fi
        echo "    ${dev}:"

        if [ -n "${mtu}" ]; then
            echo "      mtu: ${mtu}"
        fi

        case "${method}" in
            ''|static)
                : # in gen_addresses
                ;;
            dhcp)
                gen_dhcp_conf
                ;;
        esac

        case "${method6}" in
            ''|static)
                : # in gen_addresses
                ;;
            auto|dhcp)
                gen_dhcp6_conf
                ;;
            disabled)
                gen_ipv6_disable
                ;;
        esac

        _addresses=$(gen_addresses)
        if [ -n "${_addresses}" ] ; then
            echo "      addresses:"
            echo "${_addresses}"
        fi

        _routes=$(gen_routes)
        if [ -n "${_routes}" ] ; then
            echo "      routes:"
            echo "${_routes}"
        fi
    done
}
