#!/usr/bin/env bash
# ==========================================================================
#     _   _ _ ____            ____          _____
#    | | | (_)  _ \ ___ _ __ / ___|___  _ _|_   _| __ __ _  ___ ___ _ __
#    | |_| | | |_) / _ \ '__| |   / _ \| '_ \| || '__/ _` |/ __/ _ \ '__|
#    |  _  | |  __/  __/ |  | |__| (_) | | | | || | | (_| | (_|  __/ |
#    |_| |_|_|_|   \___|_|   \____\___/|_| |_|_||_|  \__,_|\___\___|_|
#
#       ---  High-Performance Connectivity Tracer (HiPerConTracer)  ---
#                 https://www.nntb.no/~dreibh/hipercontracer/
# ==========================================================================
#
# High-Performance Connectivity Tracer (HiPerConTracer)
# Copyright (C) 2015-2025 by Thomas Dreibholz
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU 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 General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Contact: dreibh@simula.no

# Bash options:
set -eu


if [ $# -ne 3 ] ; then
   echo >&2 "Usage: $0 template-users.conf mydatabase-users.conf database"
   exit 1
fi
TEMPLATE="$1"
CONFIG="$2"
DATABASE="$3"
if [[ ! "${CONFIG}" =~ (-users\.conf)$ ]] ; then
   echo >&2 "ERROR: Name must be <PREFIX>-users.conf!"
   exit 1
fi


# ====== Generate secure test user passwords ================================
if [ ! -e "${CONFIG}" ] ; then
   echo -e "\x1b[34m$(date +"%F %H:%M:%S"): Generating ${CONFIG} ...\x1b[0m"
   while read -r line ; do
      echo >&2 "$line"
      if [[ "${line}" =~ ^(.*[\"])(!.*!)([\"])$ ]] ; then
         echo "${BASH_REMATCH[1]}$(pwgen -s 128)${BASH_REMATCH[3]}"
      else
         echo "${line}"
      fi
   done <"${TEMPLATE}" | tee "${CONFIG}"
fi

# shellcheck disable=SC1090
. "${CONFIG}"


# ====== Write HiPerConTracer Importer configuration files ==================
name="$(dirname "${CONFIG}")/importer-${DATABASE}.conf"
cat >"${name}" <<EOF
# ====== Importer Configuration =============================================

# Import modes: DeleteImportedFiles MoveImportedFiles KeepImportedFiles
# DeleteImportedFiles = Delete successfully imported files
# MoveImportedFiles   = Move successfully imported files to good path
# KeepImportedFiles   = Keep successfully imported files where they are
#                       Use only for debugging! Any importer rerun will process them again!
import_mode        = MoveImportedFiles

# Regular expression to filter input files:
import_path_filter =

# Import directory and maximum search depth (1 = only the directory itself):
import_file_path   = data/
import_max_depth   = 6

# NOTE: good and bad file directories MUST NOT be a subdirectory of the
#       import directory!
bad_file_path      = bad/
good_file_path     = good/

# Sorting of files in good/bad file directories, taking levels of the
# original file name's directory hierarchy as well as of the timestamp:
move_directory_depth = 2
move_timestamp_depth = 3

# Interval for showing current importer status in output log (in s, minimum 5):
status_interval = 60
# Interval for directory garbage collection (in s, minimum 10):
gc_interval = 65
# Maximum age for unused, empty directories (in s, minimum 60):
gc_max_age = 120

# Custom table mappings (Reader:Table):
# table = Ping:Ping
# table = Traceroute:Traceroute
# table = Jitter:Jitter
EOF

for backend in MariaDB PostgreSQL MongoDB ; do
   host="${backend,,}"
   server="${host}.${DOMAIN}"
   for user in ${USERS} ; do
      database="${DATABASE}"
      if [ "${backend}" == "MongoDB" ] && [ "${user}" == "root" ] ; then
         database="admin"   # MongoDB's root user is in database "admin"!
      fi
      # shellcheck disable=SC2001
      name="$(echo "${CONFIG}" | sed -e "s/-users\.conf$/-${user}-${backend,,}.conf/")"
      passwordVariable="${user^^}_PASSWORD"
      password="${!passwordVariable}"
      if [ "${user}" == "root" ] && [ "${backend}" == "PostgreSQL" ] ; then
         user="postgres"   # The PostgreSQL root user is "postgres", not "root"!
      fi

      cat >"${name}" <<EOF
# ====== Database Server Configuration ======================================

# ----- TLS configuration options -------------------------------------------
# NOTE:
# dbcafile sets a TLS CA file.
# dbcertkeyfile sets a TLS client certificate file.
# dbconnectionflags sets TLS connection flags (space-separated):
# * NONE: default, i.e. require properly configured TLS
# * DisableTLS: disable TLS
# * AllowInvalidHostname: allow invalid hostnames in certificate
# * AllowInvalidCertificate: allow invalid certificate
# WARNING: Do *not* use these options! Instead, configure TLS properly!!
# ---------------------------------------------------------------------------


# ****** Configuration with ${backend} server: ***************
dbbackend         = ${backend}
dbserver          = ${server}
dbport            = 0
dbcafile          = ${HOME}/TestLevel1.crt
dbcrlfile         = ${HOME}/TestGlobal.crl
dbcertfile        = NONE
dbkeyfile         = NONE
dbconnectionflags = NONE
dbuser            = ${user}
dbpassword        = ${password}
database          = ${database}
dbreconnectdelay  = 5
EOF
      if [ "${backend}" == "MongoDB" ] ; then
         sed -e "s/^dbcertfile   /dbcertkeyfile/" \
             -e "/^dbkeyfile/d" \
             <"${name}" >"${name}".new && \
         mv "${name}".new "${name}"
      fi
   done
done


# ====== Write DBeaver configuration files ==================================
# shellcheck disable=SC2001
prefix="$(echo "${CONFIG}" | sed -e "s/-users\.conf$//")"
if [ -x ../make-dbeaver-configuration ] ; then
   # Running in development environment:
   ../make-dbeaver-configuration "${prefix}"-*-*.conf --join || true
else
   make-dbeaver-configuration "${prefix}"-*-*.conf --join || true
fi
