#!/bin/bash
#
#	Create config files using variables in SETENV.
#	Templates for config files have the same name with "-ORIGINAL" appended.
#
#	1. standard values (___ENVIRONMENT___, ___APPLICATION___ etc)
#	2. For any environment variable V_XYZ defined in SETENV, replace all
#	   instances of ___XYZ___ in this file with the value of the variable.
#
#
cd $(dirname $0)
. SETENV

# Update the env file for the scripts
cp SETENV Scripts/SETENV

# Remove annoying files
find . -name .DS_Store -exec rm {} \;

#	Update config files in the volumes
echo "-------------------------------------------------------------------"
echo 'Creating config files from '*-ORIGINAL' files...'
tmp=`mktemp "/tmp/$(basename $0)-tmp-$$"`
for ORIGINAL in $(find . -name '*-ORIGINAL') ; do

	seq=0
	FINAL=$(echo ${ORIGINAL} | sed 's/-ORIGINAL$//')
	here=`pwd`
	echo
	echo ${FINAL} | sed 's!^./!!' | sed 's!$!:!'

	# Replace custom values in this file
	cnt=0
	source=${ORIGINAL}
	for vvar in `compgen -v V_`; do
		# Strip off the V_
		realname=$(echo $vvar | sed "s/^V_//")

		# Replace instances of this variable
		to=${tmp}-${cnt}
		echo "     - replace ${realname}"
		sed -e "s!___${realname}___!${!vvar}!" < ${source} > ${to}
		[ $? != 0 ] && exit 1

		cnt=`expr ${cnt} + 1`
		source=${to}
	done

	# Do the standard variable replacements
	sed \
		-e "s!___ENVIRONMENT___!${ENVIRONMENT}!" \
		-e "s!___CLUSTER___!${ENVIRONMENT}!" \
		-e "s!___APPLICATION___!${APPLICATION}!" \
		-e "s!___TASKNAME___!${APPLICATION}!" \
		-e "s!___REGION___!${REGION}!" \
		-e "s!___LOGSTREAM___!${LOGSTREAM}!" \
		\
		-e "s!___DB_HOST___!${DB_HOST}!" \
		-e "s!___DB_PORT___!${DB_PORT}!" \
		-e "s!___DB_NAME___!${DB_NAME}!" \
		-e "s!___DB_USERNAME___!${DB_USERNAME}!" \
		-e "s!___DB_PASSWORD___!${DB_PASSWORD}!" \
		\
		-e "s!___REDIS_HOST___!${REDIS_HOST}!" \
		-e "s!___REDIS_PORT___!${REDIS_PORT}!" \
	< ${source} > ${FINAL}
	[ $? != 0 ] && exit 1

done

# Clean up
rm ${tmp}-*

echo ''
echo "Seems like it all worked (unless you saw an error above)."
exit 0
