#!/usr/bin/env bash
#
# lib/lvpn-avahi-anuncio
#
# 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/>.
#
#
# Anuncia o desanuncia la llave del nodo en la red local


. "${LVPN_LIBDIR}"/common

PIDFILE=${PIDFILE:-/tmp/${NETWORK}-announce.pid}
SERVICE=${SERVICE:-/etc/avahi/services/${2}.service}
SERVICE="${2}.service"

node="$(get_node_name "$1")"

touch "${PIDFILE}" 2>/dev/null || \
fatal_error "No se puede escribir el archivo de pid: %s" "${PIDFILE}"

  touch "${SERVICE}" 2>/dev/null ||
  fatal_error "No se puede escribir el archivo %s" "${SERVICE}"

  cat >"${SERVICE}" <<EOF

<?xml version="1.0" standalone='no'?>
<!DOCTYPE service-group SYSTEM "avahi-service.dtd">
<service-group>
    <name replace-wildcards="yes">${1} ${node}@${NETWORK}</name>
    <service>
        <type>_${NETWORK}._$3</type>
        <port>${nodeport:-$4}</port>
        $(cat $5 | base64 | \
          tac | \
          sed -e 's/^/<txt-record>/' \
              -e 's/$/<\/txt-record>/')
    </service>
</service-group>
EOF


exit $?
