#!/usr/bin/env bash
set -Eeuo pipefail

pids=()

term_handler() {
	set +e
	for pid in "${pids[@]:-}"; do
		if kill -0 "$pid" 2>/dev/null; then
			kill -TERM "$pid" 2>/dev/null || true
		fi
	done
	wait || true
}

trap term_handler TERM INT QUIT

/usr/bin/mysqld_safe &
pids+=("$!")

php_fpm_bin="$(find /usr/sbin -maxdepth 1 -type f -name 'php-fpm*' | sort -V | tail -n 1)"
php_fpm_conf="$(find /etc/php -path '*/php-fpm.conf' -type f | sort -V | tail -n 1)"

if [[ -z "${php_fpm_bin}" || -z "${php_fpm_conf}" ]]; then
	echo "Unable to find php-fpm binary or configuration" >&2
	exit 1
fi

"${php_fpm_bin}" --nodaemonize --fpm-config "${php_fpm_conf}" &
pids+=("$!")

nginx -g 'daemon off;' &
pids+=("$!")

# Exit when the first service exits, then stop the remaining services.
wait -n "${pids[@]}"
exit_code="$?"
term_handler
exit "${exit_code}"
