#!/usr/bin/env bash
#
# lib/lvpn-connectto
#
# 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/>.
#
#
# Agrega valores connectto a un nodo

. "${LVPN_LIBDIR}"/common

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

node="$(get_node_name "$1")"; shift
hosts=("$@")

nodedir="$(get_node_dir ${node})"

# Salir si hosts está vacío
if [[ ${#hosts[@]} -eq 0 ]]; then exit; fi

# Agregar los nodos
${LVPN} add-host ${node} "${hosts[@]}" || \
    fatal_error "No se pudieron agregar los archivos de host"

# Recorrer todos los host que se pasaron
for _connectto in "${hosts[@]}"; do
  if ! grep -q "^Address" "$(get_host_file ${_connectto})"; then
    warning "El nodo %s no tiene una ubicación pública, no será posible conectarse" "${_connectto}"
    continue
  fi

# No es necesario agregarlo dos veces
  grep -q "^ConnectTo = ${_connectto}$" "${nodedir}/tinc.conf" && continue

# Agregar la linea ConnectTo = nodo a tinc.conf
  msg "Conectar a %s" "${_connectto}"
  add_to_file "${nodedir}/tinc.conf" "ConnectTo = ${_connectto}"
done

exit $?
