#!/usr/bin/env bash
#
# lib/lvpn-update-skel
#
# 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/>.
#
#
# Actualiza el skel

. "${LVPN_LIBDIR}"/common

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

# Para cada nodo
for _node in "$@"; do
# Limpiar los nombres
  _node="$(get_node_name "${_node}")"
  _d="$(date +%Y.%m.%d)"

  ${VERBOSE} && msg "Actualizando archivos del nodo %s" ${_node}

# Obtener el directorio local
  nodedir="$(get_node_dir ${_node})"

# Por cada archivo del skel
  for _destfile in ${nodedir}/*; do
# Generar el skel local
    _skelfile="${LVPN_LIBDIR}/skel/${_destfile##*/}"

# Saltearse los archivos que no existan
    test -f "${_skelfile}" || continue

    ${VERBOSE} && msg "Archivo: %s" "${_destfile}"

# Guardar un backup
    mv "${_destfile}" "${_destfile}.${_d}.backup"

# Aplicar el "template"
# TODO encontrar un mustache liviano
    sed -e "s,{{LVPN_SUBNET}},${LVPN_SUBNET},g" \
        -e "s,{{LVPN_SUBNET6}},${LVPN_SUBNET6},g" "${_skelfile}" >"${_destfile}"

  done

  ${VERBOSE} && \
    msg "Backups guardados en %s" "$(pushd "${nodedir}" &>/dev/null; echo *.${_d}.backup; popd &>/dev/null)"

done

exit $?
