#!/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()
{
    case "${os_id}" in
        alpine)
            return 0
            ;;
        debian|ubuntu|devuan)
            return 0
            ;;
    esac

    return 1
}

configure_network()
{
    gen_resolvconf
    gen_network_configuration > /etc/network/interfaces

    case "${os_id}" in
        debian|ubuntu|devuan)
            echo "source /etc/network/interfaces.d/*.cfg" >> /etc/network/interfaces
            ;;
    esac
}

stop_network()
{
    case "${os_id}" in
        alpine)
            service networking stop || true

            # took from find_ifaces in the networking service
            _ifaces=$(\
                awk '$1 == "auto" {
                    for (i = 2; i <= NF; i = i + 1) printf("%s ", $i)
                    }' /etc/network/interfaces)

            for _iface in $_ifaces; do
                if [ "${_iface}" != 'lo' ]; then
                    /sbin/ip link set dev "${_iface}" down || true
                    /sbin/ip addr flush dev "${_iface}" || true
                fi
            done
            ;;
        debian|ubuntu|devuan)
            if [ -f "/usr/sbin/ifreload" ] ; then
                return 0
            fi

            _ifaces=$(/sbin/ifquery --list -a)

            for _iface in $_ifaces; do
                if [ "${_iface}" != 'lo' ] ; then
                    /sbin/ifdown "${_iface}"
                    /sbin/ip addr flush dev "${_iface}"
                fi
            done
            ;;
        *)
            exit 1
            ;;
    esac
}

start_network()
{
    case "${os_id}" in
        alpine)
            service networking start
            ;;
        debian|ubuntu|devuan)
            if [ -f "/usr/sbin/ifreload" ] ; then
                /usr/sbin/ifreload -a
                return 0
            fi

            _ifaces=$(/sbin/ifquery --list -a)

            for _iface in $_ifaces; do
                /sbin/ifup "${_iface}"
            done
            ;;
        *)
            exit 1
            ;;
    esac
}

reload_network()
{
    stop_network
    start_network
}

#
# 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_iface_conf()
{
    cat <<EOT
iface ${dev} inet static
  address ${ip}
  network ${network}
  netmask ${mask}
EOT

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

    if [ -n "$gateway" ]; then
        echo "  gateway ${gateway}"

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

    echo ""
}

gen_dhcp_conf()
{
    echo "iface ${dev} inet dhcp"
}

gen_alias_conf()
{
    cat <<EOT
iface ${dev} inet static
  address ${ip}
  network ${network}
  netmask ${mask}
EOT

echo ""
}

gen_iface6_conf()
{
    case "${os_id}" in
        alpine)
            cat <<EOT
iface ${dev} inet6 static
  address ${ip6}
  netmask ${ip6_prefix_length:-64}
  pre-up echo 0 > /proc/sys/net/ipv6/conf/${dev}/autoconf
  pre-up echo 0 > /proc/sys/net/ipv6/conf/${dev}/accept_ra
EOT
            ;;
        debian|ubuntu|devuan)
            cat <<EOT
iface ${dev} inet6 static
  address ${ip6}
  netmask ${ip6_prefix_length:-64}
  autoconf 0
  accept_ra 0
EOT
            ;;
    esac

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

    if [ -n "${gateway6}" ]; then
        echo "  gateway ${gateway6}"
    fi

    if [ -n "${ip6_ula}" ]; then
        cat <<EOT

iface ${dev} inet6 static
  address ${ip6_ula}
  netmask 64
EOT
    fi

    echo ""
}

gen_dhcp6_conf()
{
    if [ "${method6}" = "auto" ] ; then
        echo "iface ${dev} inet6 auto"
    else
        echo "iface ${dev} inet6 dhcp"
    fi
}

gen_alias6_conf()
{
    case "${os_id}" in
        alpine)
            cat <<EOT
iface ${dev} inet6 static
  address ${ip6}
  netmask ${ip6_prefix_length:-64}
EOT
            ;;
        debian|ubuntu|devuan)
            cat <<EOT
iface ${dev} inet6 static
  address ${ip6}
  netmask ${ip6_prefix_length:-64}
EOT
            ;;
    esac

    if [ -n "${ip6_ula}" ]; then
        cat <<EOT

iface ${dev} inet6 static
  address ${ip6_ula}
  netmask 64
EOT
    fi

    echo ""
}

gen_network_configuration()
{
    cat <<EOT
auto lo
iface lo inet loopback

EOT

    _context_interfaces=$(get_context_interfaces)

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

        skip_interface && continue

        echo "auto ${dev}"

        case "${method}" in
            ''|static)
                [ -n "${ip}" ] && gen_iface_conf
                ;;
            dhcp)
                gen_dhcp_conf
                ;;
        esac

        case "${method6}" in
            ''|static)
                [ -n "${ip6}" ] && gen_iface6_conf
                ;;
            auto|dhcp)
                gen_dhcp6_conf
                ;;
            disabled)
                :
                ;;
        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_alias_conf
                    [ -n "${ip6}" ] && gen_alias6_conf
                fi
            fi
        done
    done
}
