84 lines
1.8 KiB
Bash
84 lines
1.8 KiB
Bash
#!/usr/bin/env bash
|
|
|
|
set -euo pipefail
|
|
|
|
if [ "$#" -lt 2 ] || [ "$#" -gt 3 ]; then
|
|
echo "Usage: $0 <template-file> <env-file> [session-secret]" >&2
|
|
exit 1
|
|
fi
|
|
|
|
template_file="$1"
|
|
env_file="$2"
|
|
session_secret="${3:-}"
|
|
|
|
if [ ! -f "$template_file" ]; then
|
|
echo "Template file not found: $template_file" >&2
|
|
exit 1
|
|
fi
|
|
|
|
tmp_output="$(mktemp)"
|
|
trap 'rm -f "$tmp_output"' EXIT
|
|
|
|
target_mode="640"
|
|
if [ -f "$env_file" ]; then
|
|
target_mode="$(stat -c '%a' "$env_file" 2>/dev/null || printf '640')"
|
|
fi
|
|
|
|
if [ -f "$env_file" ]; then
|
|
awk '
|
|
function key_from(line, key) {
|
|
if (line ~ /^[[:space:]]*[A-Za-z_][A-Za-z0-9_]*=/) {
|
|
key = line
|
|
sub(/=.*/, "", key)
|
|
gsub(/^[[:space:]]+|[[:space:]]+$/, "", key)
|
|
return key
|
|
}
|
|
return ""
|
|
}
|
|
FNR == NR {
|
|
key = key_from($0)
|
|
if (key != "") {
|
|
existing[key] = $0
|
|
existing_order[++existing_count] = key
|
|
}
|
|
next
|
|
}
|
|
{
|
|
key = key_from($0)
|
|
if (key != "") {
|
|
template_seen[key] = 1
|
|
if (key in existing) {
|
|
print existing[key]
|
|
} else {
|
|
print $0
|
|
}
|
|
} else {
|
|
print $0
|
|
}
|
|
}
|
|
END {
|
|
appended = 0
|
|
for (i = 1; i <= existing_count; i++) {
|
|
key = existing_order[i]
|
|
if (!(key in template_seen)) {
|
|
if (!appended) {
|
|
print ""
|
|
print "# Vorherige zusaetzliche Eintraege"
|
|
appended = 1
|
|
}
|
|
print existing[key]
|
|
}
|
|
}
|
|
}
|
|
' "$env_file" "$template_file" > "$tmp_output"
|
|
else
|
|
cp "$template_file" "$tmp_output"
|
|
fi
|
|
|
|
if [ -n "$session_secret" ] && grep -q '^SESSION_SECRET=$' "$tmp_output"; then
|
|
sed -i "s/^SESSION_SECRET=$/SESSION_SECRET=$session_secret/" "$tmp_output"
|
|
fi
|
|
|
|
cat "$tmp_output" > "$env_file"
|
|
chmod "$target_mode" "$env_file"
|