#!/bin/sh
#
# Run by the nginx image's /docker-entrypoint.sh before nginx starts.
#
# 1. Replaces the build-time placeholders (__NAME__) in the static bundle with the values from the
#    container environment. Every one is required and must be an http(s) URL: the bundle was
#    minified with a truthy placeholder, so an empty value would not behave like an unset one at
#    build time, and a missing one would leave the contact form posting to nowhere.
# 2. The bundle's robots.txt was built with IS_DEV=false (crawling allowed, Sitemap line); a DEV/TST
#    container (IS_DEV=true) swaps it for the disallow-all version of src/pages/robots.txt.ts.
#
# A missing or malformed value stops the container instead of serving a broken site, or one that
# search engines might index (or ignore) by mistake.

set -eu

ROOT=/usr/share/nginx/html

# Keep in sync with the placeholders in the Dockerfile.
URL_VARS="NEW_MESSAGE_API_URL"

for name in $URL_VARS; do
	eval "value=\${$name:-}"

	if [ -z "$value" ]; then
		echo "$0: error: $name is not set" >&2
		exit 1
	fi

	case "$value" in
		http://*|https://*) ;;
		*)
			echo "$0: error: $name must be an http(s) URL, got: $value" >&2
			exit 1
			;;
	esac

	# Escape the characters that are special in the sed replacement below.
	escaped=$(printf '%s' "$value" | sed 's/[&|\\]/\\&/g')

	grep -rlF "__${name}__" "$ROOT" | while read -r file; do
		sed -i "s|__${name}__|${escaped}|g" "$file"
	done

	echo "$0: $name=$value"
done

case "${IS_DEV:-}" in
	true)
		printf 'User-agent: *\nDisallow: /\n' > "$ROOT/robots.txt"
		;;
	false) ;;
	*)
		echo "$0: error: IS_DEV must be true or false, got: ${IS_DEV:-<unset>}" >&2
		exit 1
		;;
esac

echo "$0: IS_DEV=$IS_DEV"
