#!/bin/bash
# Simpele check om te controleren of een IPv4/IPv6 network aanwezig is in de route table

usage() {
    echo "Usage: $0 [ipv4|ipv6|all] [IPv4 network] [IPv4 Route table] [IPv6 network] [IPv6 Route table]"
    exit 1
}

if [ "$#" -lt 2 ]; then
    usage
fi

# Default vars
TYPE=$1
IPV4_ADDR=$2
IPV4_RO_TABLE=$3
IPV6_ADDR=$4
IPV6_RO_TABLE=$5
ERROR=0
ERROR_MESSAGE=""

case "${TYPE}" in
    ipv4)
        if [[ -z "${IPV4_ADDR}" ]]; then
            echo "No IPv4 network."
            usage
        else
           if ! ip -4 ro sh table "${IPV4_RO_TABLE}" | grep -q "${IPV4_ADDR}"; then
                ERROR_MESSAGE+=" ${IPV4_ADDR} not found in routing tables |"
                ERROR=1
           fi
           if ! ip -4 ru sh table "${IPV4_RO_TABLE}" | grep -q "${IPV4_ADDR}"; then
                ERROR_MESSAGE+=" ${IPV4_ADDR} not found in rule tables |"
                ERROR=1
           fi
        fi
        ;;
    ipv6)
	    # Overrule IPV6_ADDR var
	    IPV6_ADDR=$2
        if [[ -z "${IPV6_ADDR}" ]]; then
            echo "No IPv6 network"
            usage
        else
            if ! ip -6 ro sh table "${IPV6_RO_TABLE}" | grep -q "${IPV6_ADDR}"; then
                ERROR_MESSAGE+=" ${IPV6_ADDR} not found in routing tables |"
                ERROR=1
            fi
            if ! ip -4 ru sh table "${IPV6_RO_TABLE}" | grep -q "${IPV6_ADDR}"; then
                ERROR_MESSAGE+=" ${IPV6_ADDR} not found in rule tables |"
                ERROR=1
            fi
        fi
        ;;
    all)
        if [[ -z "${IPV4_ADDR}" || -z "${IPV6_ADDR}" ]]; then
            echo "No IPv4 or IPv6 network"
            usage
        else
            # ip route show
            if ! ip -4 ro sh table "${IPV4_RO_TABLE}" | grep -q "${IPV4_ADDR}"; then
                ERROR_MESSAGE+=" ${IPV4_ADDR} not found in routing tables |"
                ERROR=1
            fi
            if ! ip -6 ro sh table "${IPV6_RO_TABLE}" | grep -q "${IPV6_ADDR}"; then
                ERROR_MESSAGE+=" ${IPV6_ADDR} not found in routing tables |"
                ERROR=1
            fi

            # ip rules show
            if ! ip -4 ru sh table "${IPV4_RO_TABLE}" | grep -q "${IPV4_ADDR}"; then
                ERROR_MESSAGE+=" ${IPV4_ADDR} not found in rule tables |"
                ERROR=1
            fi
            if ! ip -6 ru sh table "${IPV6_RO_TABLE}" | grep -q "${IPV6_ADDR}"; then
                ERROR_MESSAGE+=" ${IPV6_ADDR} not found in rule tables |"
                ERROR=1
            fi
        fi
        ;;
    *)
        echo "Invalid type"
        usage
        ;;
esac

# Error?
if [ "${ERROR}" -eq "1" ]; then
    echo "CRITITAL -${ERROR_MESSAGE}"
    exit 2
fi

# All OK
echo "OK - everything looks fine!"
exit 0
