#!/bin/bash
# Updates vnstat base list
# Updates interface name in the vnstat configuration

req=$1
if [ "$req" == "config-unknown" ]; then
   # Update non-existing Interface in the config file
   CONFIG_IFACE=$(awk -F\" '/^Interface/ {print $2;}' /etc/vnstat.conf)
   /usr/bin/ip -oneline link | /bin/grep -q "[[:blank:]]$CONFIG_IFACE:" && exit
   req="config"
fi

case "$req" in
  config)
      CONFIG_IFACE=$(/usr/bin/ip -oneline link | /bin/awk -F': ' '$2 != "lo" {print $2;}' | /bin/head -n 1)
      /bin/sed -e "/^Interface/ s/\"[^\"]*\"/\"$CONFIG_IFACE\"/" -i /etc/vnstat.conf
      ;;
  db|dbs|base|bases)
      /usr/bin/ip -oneline link | /bin/awk -F': ' '{print $2;}' | /bin/sed -e 's/@.*//' | while read iface; do
         vnstat --iface "$iface" --query > /dev/null || \
             /usr/bin/vnstat --add --iface "$iface"
      done
      ;;
  *)
     echo "Usage: $0 [bases|config]"
     echo "$0 bases  - creates or updates vnstat databases for all found network interfaces"
     echo "$0 config - set first interface as default in the config file"
     ;;
esac
