#!/usr/bin/bash
#
# Probe Endpoint Setup
# Copyright (C) 2019-2024 by Thomas Dreibholz
#
# This program 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.
#
# This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Contact: dreibh@simula.no
#

# Bash options:
set -e


# Example:
#
# Probe-Endpoint-Setup add 1000 gamma1 11.254.1.50 11.254.3.1 0x00030001 192.168.3.1
# Probe-Endpoint-Setup add 1001 gamma2 11.254.1.50 11.254.3.1 0x00030002 192.168.3.2
#
# TABLE=1000
# FORWARDING_INTERFACE="tdr3-1"
# FORWARDING_LOCAL="11.254.1.50"
# FORWARDING_REMOTE="11.254.3.1"
# FORWARDING_GRE_KEY="0x00030001"
# FORWARDING_TTL="64"
# FORWARDING_MTU="1280"
# COLLECTOR_ADDRESS="192.168.3.1"


if [ "$#" -ne 7 ] ; then
   echo >&2 "Usage: $0 add|remove table_id fwd_interface fwd_local fwd_remote fwd_gre_key collector_addr"
   exit 1
fi

ACTION="$1"
if [ "$ACTION" != "add" -a "$ACTION" != "remove" ] ; then
   echo >&2 "ERROR: Bad action \"$ACTION\"."
   exit 1
fi

TABLE="$2"
PREFERENCE="100"

FORWARDING_INTERFACE="$3"
FORWARDING_LOCAL="$4"
FORWARDING_REMOTE="$5"
FORWARDING_GRE_KEY="$6"
FORWARDING_TTL="64"
FORWARDING_MTU="1280"

COLLECTOR_ADDRESS="$7"


remove-sniffer ()
{
   ip route del default dev "$FORWARDING_INTERFACE" table "$TABLE" || true
   ip rule del from "$COLLECTOR_ADDRESS" lookup "$TABLE" pref "$PREFERENCE" || true
   ip tunnel del "$FORWARDING_INTERFACE" || true
}


install-sniffer ()
{
   remove-sniffer >/dev/null 2>&1

   ip tunnel add "$FORWARDING_INTERFACE" mode gre key "$FORWARDING_GRE_KEY" local "$FORWARDING_LOCAL" remote "$FORWARDING_REMOTE" ttl "$FORWARDING_TTL"
   ip link set dev "$FORWARDING_INTERFACE" up mtu "$FORWARDING_MTU"
   ip addr add "$COLLECTOR_ADDRESS/32" dev "$FORWARDING_INTERFACE" valid_lft forever nodad

   ip rule add from "$COLLECTOR_ADDRESS" lookup "$TABLE" pref "$PREFERENCE"
   ip route add default dev "$FORWARDING_INTERFACE" table "$TABLE"
}


if [ "$ACTION" = "add" ] ; then
   install-sniffer
else
   remove-sniffer
fi
ip -4 route flush cache
