#!/bin/bash

# Copyright (c) 2017 SUSE Linux GmbH
#
# This file is part of cloud-netconfig.
#
# cloud-netconfig is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# cloud-netconfig is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with cloud-netconfig.  If not, see <http://www.gnu.org/licenses/

logger -t "cloud-netconfig-cleanup" "cleaning up routing policies"

get_all_addresses()
{
    ip $1 -o addr show | \
    while read -r idx iface type addr test ; do
        if [[ "$iface" != "lo" ]]; then
            echo "${addr%/*}"
        fi
    done
}

contains_element()
{
    local elem
    for elem in "${@:2}"; do
        [[ "$elem" == "$1" ]] && return 0
    done
    return 1
}

remove_unused_rules()
{
    ADDRESSES=($(get_all_addresses $1))
    ip $1 rule show | \
    while read -r prio from ip lookup table rest ; do
        [[ "$ip" == "all" ]] && continue
        if ! contains_element "$ip" "${ADDRESSES[@]}"; then
            # address not assigned, remove policy rule
            ip $1 rule del priority ${prio%%:} from $ip
        fi
    done
}

remove_unused_rules "-4"
remove_unused_rules "-6"
