#!/bin/bash
# =============================================================================
# clickhouse-init.sh — Pre-process shared SQL files for integration testing
#
# Copies SQL from /initdb-src/ to /tmp, patches credentials, then executes.
# =============================================================================
set -e

SRC_DIR="/initdb-src"
TMP_DIR="/tmp/initdb-patched"
mkdir -p "$TMP_DIR"

for f in "$SRC_DIR"/*.sql; do
    [ -f "$f" ] || continue
    base=$(basename "$f")
    echo "[init] Patching $base"
    sed \
        -e "s/USER 'admin'/USER 'default'/g" \
        -e "s/PASSWORD 'CHANGE_ME'/PASSWORD ''/g" \
        -e "s/PASSWORD 'ChangeMe'/PASSWORD ''/g" \
        "$f" > "$TMP_DIR/$base"
done

for f in "$TMP_DIR"/*.sql; do
    [ -f "$f" ] || continue
    echo "[init] Executing $(basename "$f")"
    clickhouse-client --multiquery < "$f"
done

echo "[init] All SQL files executed — initialisation terminée"
