#!/usr/bin/env bash
#
# lib/lvpn-d3
#
# Copyright (c) 2011-2013 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/>.
#
#
# Exporta los nodos y enlaces en JSON para D3 <http://d3js.org> TODO
#convertir a un exportador genérico set -e

. "${LVPN_LIBDIR}"/common

requires tail ps sudo killall wc cut nl sed mktemp

while getopts "h" arg; do
    case $arg in
        h) help ${self} ; exit 0;;
    esac
done
let OPTIND--; shift ${OPTIND}

tmpfile="$(mktemp /tmp/$self-XXXX.log)"

# Monitorear el log
tail -f -n1 /var/log/tinc.$(basename ${TINC}).log > ${tmpfile} &
tailpid=$(ps -o pid -C tail --no-header)

# Limpia la cache de nodos y pide la lista de nodos y enlaces
for _signal in WINCH USR2; do
    sudo killall -SIG${_signal} tincd 2>/dev/null
done

# Esperar la lista
while [ $(wc -l ${tmpfile} | cut -d " " -f1) -lt 5 ]; do
    sleep 1s
done

# Matar el tail
kill ${tailpid}

# Grep ": $node at" limpiar, ordenar y numerar (para los indices)
# Salida: index:nodo
nodes=($(grep -o ": \+[^ ]\+ at" ${tmpfile} | \
            grep -o " [^ ]\+ " | \
            tr -d " " | \
            sort -u | \
            nl -v0 -s:))

# Grep "$node to $othernode at" y limpiar
links=($(grep -o "[^ ]\+ to [^ ]\+ at" ${tmpfile} | \
            sed -e "s/ to /:/" -e "s/ at$//" | \
            sort -u))

# Extrae el indice de index:name
get_index() {
    needle=$1
    echo "${nodes[@]}" | grep -o "[0-9]\+:${needle}" | cut -d":" -f1
}

# Array de nodos
json='{"nodes":['
for _n in ${nodes[@]}; do
    json+='{"index":'${_n%%:*}',"name":"'${_n#*:}'"},'
done

# Array de enlaces
# TODO es bastante lento
json+='],"links":['
for _l in ${links[@]}; do
    json+='{"source":'$(get_index ${_l%%:*})',"target":'$(get_index ${_l#*:})'},'
done
json+=']}'

# Limpiar comas extra
echo $json | sed "s/},]/}]/g"

rm ${tmpfile}

exit $?
