#!/bin/sh

if [ $$ == 1 ]; then
	echo "Startup script was run as init, re-execing using tini."
	exec /sbin/tini -- $0 "$@"
fi

# For backward compatibility, set NGINX_BEHIND_PROXY if not defined but BEHIND_PROXY is.
if [ -z "$NGINX_BEHIND_PROXY" && -n "$BEHIND_PROXY" ] ; then
  NGINX_BEHIND_PROXY="true"
fi

echo "Generating templated nginx configuration..."
if [ "$NGINX_RECORDINGS_ONLY" = "true" ] ; then
	echo "Using nginx recordings only configuration template."
	nginx_template=/etc/nginx/conf.d/scalelite-recordings-only.template
elif [ "$NGINX_BEHIND_PROXY" = "true" ] ; then
	echo "Using proxy configuration template."
	nginx_template=/etc/nginx/conf.d/scalelite-proxy.template
elif [ "$NGINX_SSL" = "true" ] ; then
	echo "Using SSL configuration template."
	nginx_template=/etc/nginx/conf.d/scalelite-ssl.template
else
	echo "Using non-SSL configuration template."
	nginx_template=/etc/nginx/conf.d/scalelite.template
fi
envsubst '$URL_HOST' <$nginx_template >/etc/nginx/conf.d/scalelite.conf
unset nginx_template

mkdir -p /run/nginx

echo "Starting nginx periodic reload process..."
while :; do
	sleep 6h
	echo "Reloading nginx..."
	nginx -s reload
done &


echo "Starting nginx..."
exec nginx -g 'daemon off;'
