luanti-web/site_generator/functions/01_utils.sh
2025-06-21 15:58:52 +02:00

69 lines
2.1 KiB
Bash

#!/bin/bash
# 01_utils.sh - Grundlegende Hilfsfunktionen
# === Logging Funktion ===
log_message() {
local msg
msg="$(date '+%Y-%m-%d %H:%M:%S') - $1"
# Prüft, ob stdout ein Terminal ist, um "tee" nur bei interaktiver Ausführung zu nutzen
if [ -t 1 ]; then
echo "${msg}" | tee -a "$LOG_FILE"
else
echo "${msg}" >> "$LOG_FILE"
fi
}
# === Hilfsfunktionen für Platzhalter ===
create_placeholder_file() {
local fp="$1"
local dc="$2"
if [ ! -f "$fp" ]; then
mkdir -p "$(dirname "$fp")"
echo -e "$dc" > "$fp"
log_message "Platzhalterdatei erstellt: $fp"
fi
}
get_config_value_from_file() {
local cf="$1"
local k="$2"
local dv="${3:-}"
local v
if [ ! -f "$cf" ]; then echo "$dv"; return; fi
# Robuste Extraktion, die Kommentare, Leerzeichen und Anführungszeichen berücksichtigt
v=$(grep -E "^\s*${k}\s*=" "$cf" | tail -n 1 | sed -e 's/\s*#.*//' -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' | cut -d'=' -f2- | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' -e 's/^"//' -e 's/"$//' -e "s/^'//" -e "s/'$//")
if [ -n "$v" ]; then echo "$v"; else echo "$dv"; fi
}
# === Template Rendering Funktion ===
render_template() {
local template_path="$1"
local output_path="$2"
shift 2
local replacements=("$@")
if [ ! -f "$template_path" ]; then
log_message "FEHLER: Template-Datei nicht gefunden: ${template_path}"
return 1
fi
local template_content
template_content=$(<"$template_path")
for ((i=0; i<${#replacements[@]}; i+=2)); do
local key_name="${replacements[i]}"
local key="%%${key_name}%%"
local value="${replacements[i+1]}"
# Manuelle Ersetzung in einer Schleife, um mehrzeilige Inhalte und mehrfache Vorkommen zu unterstützen
local new_content=""
while [[ "$template_content" == *"$key"* ]]; do
new_content+="${template_content%%$key*}${value}"
template_content="${template_content#*$key}"
done
template_content="${new_content}${template_content}"
done
echo "$template_content" > "$output_path"
return $?
}