#!/bin/bash

set -euo pipefail

function p4() {
    local pingout
    local pingret

    set +e
    pingout=$(ping -c4 -W1 "$@")
    pingret=$?
    set -e

    if [ "$pingret" -ne 0 ]
    then
        echo "$pingout"
        exit 1
    else
        echo "OK: $@"
    fi
}

function ping_vlan1() {
    # Vision
    p4 192.168.7.3 &
    # EMU
    p4 192.168.7.5 &
    # SW1
    p4 192.168.7.70 &
    # SW3
    p4 192.168.7.72 &
}

function ping_vlan10() {
    # Vision
    p4 192.168.8.3 &
    p4 192.168.8.4 &
    # EMU
    p4 192.168.8.5 &
    # Lidars
    p4 192.168.8.20 &
    p4 192.168.8.21 &
    # PTP Gateway
    #p4 192.168.8.30 &
    #p4 192.168.8.31 &
}

function ping_vlan20() {
    # Vision
    p4 192.168.9.3 &
    p4 192.168.9.4 &
    # EMU
    p4 192.168.9.5 &
    # Lidars
    p4 192.168.9.20 &
    p4 192.168.9.21 &
    # PTP Gateway
    #p4 192.168.9.30 &
    #p4 192.168.9.31 &
}

function ping_vlan30() {
    # Vision
    p4 192.168.10.3 &
    p4 192.168.10.4 &
    # EMU
    p4 192.168.10.5 &
    # Lidars
    p4 192.168.10.20 &
    p4 192.168.10.21 &
    # PTP Gateway
    #p4 192.168.10.30 &
    #p4 192.168.10.31 &
}

function ping_vlan40() {
    # Vision
    p4 192.168.11.3 &
    p4 192.168.11.4 &
    # EMU
    p4 192.168.11.5 &
    # EMU MON
    p4 192.168.11.6 &
    # Lidars
    p4 192.168.11.20 &
    p4 192.168.11.21 &
    # PTP Gateway
    #p4 192.168.11.30 &
    #p4 192.168.11.31 &
}

function ping_vlan50() {
    # Security gateways
    p4 192.168.12.50 &
    p4 192.168.12.51 &
    # SW2
    p4 192.168.6.71 &
    # SW4
    p4 192.168.6.73 &
}

# Ensure all interfaces are up.
sudo ip link set eth0 up
sudo ip link set eth1 up
sudo ip link set eth2 up
sudo ip link set eth3 up

echo "Test default connectivity"
ping_vlan1
ping_vlan10
ping_vlan20
ping_vlan30
ping_vlan40
ping_vlan50
wait

# Turn off link on all interfaces
sudo ip link set eth0 down
sudo ip link set eth1 down
sudo ip link set eth2 down
sudo ip link set eth3 down

# Turn up interfaces one by one and test the relevant VLANs
echo "Test eth0 connectivity"
sudo ip link set eth0 up
sleep 1
ping_vlan1
ping_vlan10
ping_vlan30
wait

sudo ip link set eth0 down

echo "Test eth1 connectivity"
sudo ip link set eth1 up
sleep 1
ping_vlan20
ping_vlan40
ping_vlan50
wait

sudo ip link set eth1 down

echo "Test eth2 connectivity"
sudo ip link set eth2 up
sleep 1
ping_vlan1
ping_vlan10
ping_vlan30
wait

sudo ip link set eth2 down

echo "Test eth3 connectivity"
sudo ip link set eth3 up
sleep 1
ping_vlan20
ping_vlan40
ping_vlan50
wait

sudo ip link set eth3 down

# Restore link on all interfaces
sudo ip link set eth0 up
sudo ip link set eth1 up
sudo ip link set eth2 up
sudo ip link set eth3 up
