#!/usr/bin/env bash
#
# lib/exec/install
#
# Copyright (c) 2020-     RAP <contacto@partidopirata.com.ar>
# Copyright (c) 2011-2016 LibreVPN <vpn@hackcoop.com.ar>
#
# 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/>.

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

. "${RAP_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 tincd

while getopts "dhvrn" 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}

NODE="$(get_node_name "${1:-$HOSTNAME}")"
nodedir="$(get_node_dir "${NODE}")"

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

if test -d "${RAP_NETWORKSDIR}/defaults"; then
  msg "Copiando configuraciones por defecto"
  for config in "${RAP_NETWORKSDIR}"/defaults/*; do
    cp -n "${config}" "${nodedir}/config/"
  done
fi

# Setear la MAC si no existía ya
if ! test -f "${nodedir}/config/mac"; then
  msg "Estableciendo MAC"
  get_node_file "${1}" | xargs cat | public_key_to_mac > "${nodedir}/config/mac"
fi

msg "Instalando en el sistema..."
${sudo} mkdir -p "${TINC}"
${sudo} rsync -a --no-owner \
              --no-group \
              --exclude="*.backup" \
              --exclude="*~" \
              --copy-unsafe-links \
              --delete-after \
              ${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
type systemctl &>/dev/null \
  && ${sudo} systemctl enable --now tinc.service tinc@${NETWORK}.service

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

# Instalar el script de reconexión de tincd
test -d /etc/NetworkManager/dispatcher.d && \
  ${sudo} install -Dm 750 -o root -g root ${RAP_SKELDIR}/50_tincd /etc/NetworkManager/dispatcher.d/

if test -f /etc/tinc/nets.boot ; then
  if ! grep -q "^${NETWORK}$" /etc/tinc/nets.boot; then
    msg "Iniciando sysVinit"

    echo "${NETWORK}" | ${sudo} tee -a /etc/tinc/nets.boot >/dev/null
    ${sudo} update-rc.d tinc defaults
    ${sudo} service tinc start
  fi
fi

# Recargar los cambios en la configuración
if pgrep tincd &>/dev/null; then
  msg "Recargando tincd..."
  for signal in WINCH HUP ALRM; do
    ${sudo} tincd -n ${NETWORK} -k ${signal}
  done
fi

exit $?
