#!/bin/bash -e
set -eo pipefail
shopt -s nullglob

SERVICES=${WAIT_SERVICES:=''}
TIMEOUT=${WAIT_TIMEOUT:='15'}

if [[ ! -z $SERVICES ]] ; then
    for service in $SERVICES ; do
        wait-for-it -t $TIMEOUT $service >&2
    done
fi
# usage: file_env VAR [DEFAULT]
#    ie: file_env 'XYZ_DB_PASSWORD' 'example'
# (will allow for "$XYZ_DB_PASSWORD_FILE" to fill in the value of
#  "$XYZ_DB_PASSWORD" from a file, especially for Docker's secrets feature)
file_env() {

	local var="$1"
	local fileVar="${var}_FILE"
	local def="${2:-}"
	if [ "${!var:-}" ] && [ "${!fileVar:-}" ]; then
		echo "Both $var and $fileVar are set (but are exclusive)" >&2
	fi
	local val="$def"
	if [ "${!var:-}" ]; then
		val="${!var}"
	elif [ "${!fileVar:-}" ]; then
		val="$(< "${!fileVar}")"
	fi
	cat >> /etc/bash.bashrc <<EOF
export ${var}=${val}
EOF
	echo "the value of variable ${var} is set" >&2
  # make them also available in preparatory steps until container starts
  export ${var}=${val}
	unset "$fileVar"
}

file_env "OS_PASSWORD"
file_env "DJANGO_PASSWORD"

eval "/opt/eoxserver/eoxserver-entrypoint.sh $@"
