#!/usr/bin/env bash
# Copy every services/**/*.env.example to *.env and fill in random secrets.
# Existing *.env files are never touched, so this is safe to re-run.
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
SERVICES_DIR="${ROOT_DIR}/infrastructure/services"

random_value() {
	openssl rand -hex 16
}

mapfile -d '' -t examples < <(find "${SERVICES_DIR}" -type f -name '*.env.example' -print0 | sort -z)

created=0
skipped=0

for example in "${examples[@]}"; do
	target="${example%.example}"
	if [[ -f "${target}" ]]; then
		skipped=$((skipped + 1))
		continue
	fi
	cp "${example}" "${target}"
	created=$((created + 1))
done

mapfile -d '' -t targets < <(find "${SERVICES_DIR}" -type f -name '*.env' -print0)

declare -A generated
tokens="$(grep -hoE '__GENERATE_[A-Z0-9_]+__' "${targets[@]}" 2>/dev/null | sort -u || true)"

for token in ${tokens}; do
	if [[ -z "${generated[${token}]:-}" ]]; then
		generated[${token}]="$(random_value)"
	fi
	value="${generated[${token}]}"
	for f in "${targets[@]}"; do
		if grep -qF -- "${token}" "${f}" 2>/dev/null; then
			sed -i "s#${token}#${value}#g" "${f}"
		fi
	done
done

echo "Created ${created} env file(s), left ${skipped} existing one(s) untouched."

remaining="$(grep -rlF 'CHANGEME_' "${targets[@]}" 2>/dev/null || true)"
if [[ -n "${remaining}" ]]; then
	echo
	echo "These files still need a value you must fill in by hand:"
	echo "${remaining}"
fi
