#!/bin/bash
#
# lvpn
#
# Copyright (c) 2011-2014 LibreVPN <vpn@hackcoop.com.ar>
#
# See AUTHORS for a list of contributors
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU Affero General
# Public License along with this program.  If not, see
# <http://www.gnu.org/licenses/>.
#
# Agregar a collectd.conf
#
# <Plugin exec>
#   Exec "daemon:daemon" "/usr/bin/collectd-lvpn" "lvpn" "63"
# </Plugin>

NETWORK="${1:-lvpn}"
DOT="/tmp/${NETWORK}.dot"
INTERVAL="${2:-63}"

if test ! -r "${DOT}" ; then
  echo "No existe ${DOT} o no se puede leer, agregá 'GraphDumpFile = ${DOT}' en tinc.conf"
  exit 1
fi

# tipo_datos tipo_valor valor
function putval() {
  stdbuf --output=L \
  printf "PUTVAL \"%s/%s/%s-%s\" interval=%d N:%d\n" \
         "${COLLECTD_HOSTNAME:-${HOSTNAME}}" \
         "${NETWORK}" \
         "${1}" "${2}" \
         "${INTERVAL}" \
         "${3}"
}

# El script duerme para siempre y cuando se despierta escupe comandos de
# collectd
while sleep ${INTERVAL}; do
  # obtener la cantidad de nodos
  nodes=$(grep label "${DOT}" | cut -d" " -f1 | tr -d "\t" | wc -l)
  # y guardarlos
  putval "gauge" "nodes" "${nodes}"

  unknown=$(lvpn unknown-peers | wc -l)
  putval "gauge" "unknown-peers" "${unknown}"
done
