#!/usr/bin/env bash
#
# lib/exec/add-host
#
# 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/>.

. "${RAP_LIBDIR}"/common

FORCE=false
while getopts "fhd" arg; do
  case $arg in
    f) FORCE=true ;;
    h) help ${self} ; exit 0;;
  esac
done
let OPTIND--; shift ${OPTIND}

node="$(get_node_name "$1")"; shift
nodedir="$(get_node_dir ${node})"

hosts=("$@")

# Recorrer todos los host que se pasaron
for _host in "${hosts[@]}"; do
# Generar el archivo y encontrarlo, saltear si no existe
  _hostfile="$(get_host_file "${_host}")"
  _hostdest="${nodedir}/hosts/${_host}"

  if test ! -f "${_hostfile}"; then
    error "El archivo host de %s no existe, salteando..." ${_host}
    continue
  fi

# Saltear si no el host existe y no estamos forzando o actualizando
  if test -e "${_hostdest}"; then
    ${FORCE} && rm -f "${nodedir}/hosts/${_host}"
    ${FORCE} || continue
  fi

  msg "Copiando el archivo host de %s" ${_host}
  # Vincular el contenido del archivo
  ln -s "${_hostfile}" "${nodedir}/hosts/${_host}"

  if test -f "${_hostfile}-up"; then
    ln "${_hostfile}-up" "${nodedir}/hosts/${_host}-up"
  fi

  if test -f "${_hostfile}-down"; then
    ln "${_hostfile}-down" "${nodedir}/hosts/${_host}-down"
  fi
done

exit $?
