#!/bin/bash
set -euo pipefail

CONF_FILE="/opt/dosis2/etc/postgresql/10/conf.d/99-custom-postgresql.conf"
MODE="0644"
MAX_BYTES=65536   # 64 KB safety limit

# Read stdin to temp file
TMP_FILE="$(mktemp)"

# Ensure temp file is cleaned up
trap 'rm -f "$TMP_FILE"' EXIT

# Read input (with size limit)
dd if=/dev/stdin of="$TMP_FILE" bs=1 count="$MAX_BYTES" status=none || true

# If input exceeded MAX_BYTES, stdin still has data
if [ "$(wc -c < "$TMP_FILE")" -gt "$MAX_BYTES" ]; then
    echo "Input too large" >&2
    exit 1
fi

# Atomically replace config
/usr/bin/install -o postgres -g postgres -m "$MODE" "$TMP_FILE" "$CONF_FILE"
