#!/bin/bash

set -eu
set -o pipefail

running_dir="$(dirname "$(readlink -f "$0")")"
wg_interface="$(grep 'tunnel_id' "$running_dir/config.ini" \
                     | sed -r 's/[^=]+=\s*//')"

assist() {
    cat <<EOF
Usage: $0 <action> [<ip>]

Actions:
   add <ip>     Add a route to the tunnel for this ip
   del <ip>     Remove a route to the tunnel for this ip
   reload       Sync running tunnel config with configuration on disk
EOF
    exit "$1"
}

add() {
    ip route add "$1" dev "$wg_interface" scope link
}

del() {
    ip route del "$1" dev "$wg_interface" scope link
}

reload() {
    systemctl reload "wg-quick@$wg_interface.service"
}

if [ "$#" = 0 ]; then
    assist 0
fi

action="$1"
shift

case "$action" in
    add )
        add "$1"
        ;;
    del )
        del "$1"
        ;;
    reload )
        reload
    ;;
esac