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

# Terminar ante el menor error
set -e

# Habilitar debug tan pronto como sea posible si se usa -d en algún lado
echo "$*" | grep -q " -\([a-z]\+\)\?d" && set -x

# Comprueba si los programas necesarios existen en el sistema
requires() {
    local missing=()
    local bin
    for bin in "$@"; do
        if ! type "$bin" &>/dev/null; then
            missing+=("$bin")
        fi
    done

    if [[ ${#missing[@]} -ne 0 ]]; then
        error "Los siguientes programas no se encuentran en PATH: ${missing[*]}"
        warning "Es posible que tengas que instalarlos usando tu gestor de paquetes, intentar usar sudo, o cambiar al usuario root."
        exit 1
    fi
}

trap_exit() {
    msg "ARGH! Algo pasó" 1>&2
    exit 1
}

trap 'trap_exit' TERM HUP QUIT INT ERR

. "${RAP_LIBDIR}/msg"

self="$(basename $0)"

# Agrega una linea a un archivo
add_to_file(){
    f=$1; shift

    echo "$*" >>"$f"
}

# Obtiene el directorio del nodo
# $1 nombre del nodo
get_node_dir() {
    node="$(get_node_name "$1")"
    dir="${RAP_NETWORKSDIR}/${node}"

    if [ ! -d "${dir}" ] || [ ! -f "${dir}/tinc.conf" ]; then
        fatal_error "El nodo no existe o es inválido"
    fi

    echo "${dir}"
}

# Obtiene el archivo del nodo en el directorio del nodo
get_node_file() {
    node="$(get_node_name "$1")"
    dir="$(get_node_dir "$1")"
    file="${dir}/hosts/${node}"

    if [ ! -f "${file}" ]; then
        fatal_error "El archivo host de %s no existe" "$1"
    fi

    echo "${file}"
}

# Recibe un texto y elimina todos los caracteres no alfanuméricos
sanitize () {
  tr -cd "[:alnum:]"
}

# Convertir texto a minúsculas
lowercase () {
  tr "[:upper:]" "[:lower:]"
}

# Convierte llaves públicas en MAC
public_key_to_mac () {
  grep -E "^[A-Za-z0-9/+=]+$" \
    | base64 -d \
    | sha256sum \
    | cut -d " " -f 1 \
    | cut -b 1-12 \
    | sed -re "s/../02:&:/g" \
    | cut -d : -f 1-6
}

# Limpia el hostname
# @see tincd.conf(5)
get_node_name() {
  echo "$1" | cut -d "." -f 1 | sanitize | lowercase
}

get_host_file() {
  node="$(get_node_name "${1}")"
  test -f "${RAP_HOSTS}/${node}" || \
    error "El archivo host de %s no existe" "$node" || \
    return 1

  echo "${RAP_HOSTS}/${node}"
}

# Obtiene un evento válido
get_event() {
  echo "$1" | grep -qE "^host|subnet|tinc$" && echo "$1"
}

# Obtener un script
get_script() {
  script_dir="${RAP_SKELDIR}/scripts"

  test -f "${script_dir}/$1" && echo "${script_dir}/$1"
}

if $root ; then
# Salir si no se es root y no existe sudo, sino usarlo
  if ! test -w /; then
    if ! type sudo &>/dev/null; then
      fatal_error "Correr como root"
    else
      export sudo=sudo
    fi
  fi
fi

run_post_script(){
  if test -x "${RAP_EXEC_HOOKDIR}/${NETWORK}/post-${RAP_COMMAND}" ; then
    msg "Ejecutando post comandos:"
    exec ${RAP_EXEC_HOOKDIR}/${NETWORK}/post-${RAP_COMMAND}
  fi
}
