#!/usr/bin/env bash
#
# lib/lvpn-install
#
# 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/>.
#
#
# Sincroniza los nodos de un nodo remoto o local
# Necesita acceso SSH, pensado para sincronizar nodos en un router con *WRT
# No usamos rsync porque no existe

# Este script necesita root (ver common)
root=true

. "${LVPN_LIBDIR}"/common

# Por las dudas, no acepta TINC vacío o de una sola letra ("/")
test "${#TINC}" -lt 2 && fatal_error "La variable TINC está vacía"

requires rsync find

while getopts "hvrn" arg; do
  case $arg in
    h) help ${self} ; exit 0;;
    v) VERBOSE=-v ;;
    n) DRYRUN=--dry-run ; VERBOSE=-v ;;
    r) DELETE=--delete-after ;;
  esac
done
let OPTIND--; shift ${OPTIND}

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

# Crear el directorio de scripts
mkdir -p "${nodedir}/scripts"

msg "Instalando en el sistema..."
${sudo} mkdir -p "${TINC}"
${sudo} rsync -a --no-owner \
              --no-group \
              --exclude="*.backup" \
              ${VERBOSE} ${DELETE} ${DRYRUN} \
              "${nodedir}/" "${TINC}/"

# No tenemos que hacer nada más si estamos con dry-run
test -n "${DRYRUN}" && exit

# Chequear permisos
msg "Chequeando permisos..."
${sudo} chown -R root:root "${TINC}"
${sudo} find "${TINC}" -type d -exec chmod 755 {} \;
${sudo} find "${TINC}" -type f -exec chmod 644 {} \;
${sudo} find "${TINC}" -name '*-up' -exec chmod 755 {} \;
${sudo} find "${TINC}" -name '*-down' -exec chmod 755 {} \;
${sudo} find "${TINC}" -name 'run-script' -exec chmod 755 {} \;
${sudo} find "${TINC}/scripts" -type f -exec chmod 755 {} \;
${sudo} chmod 600 "${TINC}/rsa_key.priv"

# Habilitar tinc en el sistema
find_init_system | while read init_system init_file; do
  case $init_system in
   deb)
      grep -q ${NETWORK} "${init_file}" || \
      $sudo sh -c "echo ${NETWORK} >>${init_file}"

# Habilitar el log y cambiar a un usuario sin privilegios
      grep -q "^EXTRA=" /etc/default/tinc || \
      $sudo sh -c "echo 'EXTRA=\"${TINCD_FLAGS}\"' >>/etc/default/tinc"
      ;;
    systemd)
# Instalar el .service desde el skel
      sed "s/{{TINCD_FLAGS}}/${TINCD_FLAGS}/g" \
           ${LVPN_LIBDIR}/skel/tincd@.service | \
           ${sudo} tee ${init_file} >/dev/null
      ;;
    unknown)
      warning "Tu sistema de inicio de tinc es desconocido, tenés que habilitar el demonio a mano o reportar un bug :)" ;;
  esac
done

# Agregar avahi en nsswitch.conf
if [ -f /lib/libnss_mdns.so.2 ]; then
  grep -q "mdns" /etc/nsswitch.conf || \
  $sudo sed -e "s/^hosts:.*$/#&\nhosts: files mdns_minimal [NOTFOUND=return] dns mdns/" \
            -i /etc/nsswitch.conf
else
  tip "Es necesario instalar nss-mdns para poder resolver nombres .local"
fi

# Instalar logrotate
test -d /etc/logrotate.d && \
  ${sudo} cp ${LVPN_LIBDIR}/skel/logrotate.conf /etc/logrotate.d/tincd.conf

# Instalar el script de reconexión de tincd
test -d /etc/NetworkManager/dispatcher.d && \
  ${sudo} cp ${LVPN_LIBDIR}/skel/50_tincd /etc/NetworkManager/dispatcher.d/

# Recargar los cambios en la configuración
if pgrep tincd &>/dev/null; then
  msg "Recargando tincd..."
  ${sudo} ${LVPN_LIBDIR}/skel/50_tincd ${NETWORK} up
fi

$sudo which avahi-daemon &>/dev/null || \
  tip "Se recomienda instalar avahi-daemon"

exit $?
