#!/bin/sh

if ! command -v jq 2>&1 >/dev/null
then
        echo No jq. exiting...
        exit 1
fi

install_ipcalc()
{
    if grep 'Ubuntu' /etc/os-release 2>&1 >/dev/null
    then
        apt install -y --no-install-recommends ipcalc
    fi
}

if ! command -v ipcalc 2>&1 >/dev/null
then
    install_ipcalc
fi

IPCALC=$(command -v ipcalc)


NICS=$(jq -M '.nics[]' /etc/pear/pear_monitor/config.json | tr -d '"')

for N in $NICS
do
    IP6=$(ip -6 -j address show primary | jq -M '.[] | select(.ifname=="'"$N"'").addr_info[] | select(.scope=="global") | .local as $local | (.prefixlen | tostring) as $prefixlen | {$local, $prefixlen}')

    if [ -z "$IP6" ]
    then
        continue
    fi

    SRC_IP6=$(echo "$IP6" | jq -M -r '.local+"/"+.prefixlen' )
    if [ -n "$IPCALC" ]
    then
        SRC_IP6=$($IPCALC -n $SRC_IP6 | grep Prefix | awk '{print $2}')
    fi

    ip -6 rule flush lookup $N
    ip -6 rule add from $SRC_IP6 lookup $N priority 1024
    ip -6 rule add to $SRC_IP6 lookup $N priority 1024

    logger -p local0.notice -t ${0##*/}[$$] "Added rules for $N address $SRC_IP6"
done

