#!/bin/bash
#set -e

: ${ETHERPAD_DB_USER:=root}
if [ "$ETHERPAD_DB_USER" = 'root' ]; then
	: ${ETHERPAD_DB_PASSWORD:=$MYSQL_ENV_MYSQL_ROOT_PASSWORD}
fi
: ${ETHERPAD_DB_NAME:=etherpad}

ETHERPAD_DB_NAME=$( echo $ETHERPAD_DB_NAME | sed 's/\./_/g' )

if [ -z "$ETHERPAD_DB_PASSWORD" ]; then
	echo >&2 'error: missing required ETHERPAD_DB_PASSWORD environment variable'
	echo >&2 '  Did you forget to -e ETHERPAD_DB_PASSWORD=... ?'
	echo >&2
	echo >&2 '  (Also of interest might be ETHERPAD_DB_USER and ETHERPAD_DB_NAME.)'
	exit 1
fi

: ${ETHERPAD_TITLE:=Etherpad}
: ${ETHERPAD_PORT:=9001}

cat settings.json
if [ ! -f settings.json ]; then
	
	cat <<- EOF > settings.json
	{
		"title": "${ETHERPAD_TITLE}",
		"ip": "0.0.0.0",
		"port": ${ETHERPAD_PORT},
		"maxAge": "${ETHERPAD_MAXAGE:-3600}",
		"minify": true,
		"dbType": "postgres",
		"dbSettings": {
						"user": "etherpad",
						"host": "${ETHERPAD_DB_HOST}",
						"port": 5432,
						"password": "${ETHERPAD_DB_PASSWORD}",
						"database": "${ETHERPAD_DB_NAME}",
						"charset": "utf8mb4"
						},
	EOF

	if [ $ETHERPAD_ADMIN_PASSWORD ]; then

		: ${ETHERPAD_ADMIN_USER:=admin}

		cat <<- EOF >> settings.json
		  "users": {
		    "${ETHERPAD_ADMIN_USER}": {
		      "password": "${ETHERPAD_ADMIN_PASSWORD}",
		      "is_admin": true
		    }
		  },
		EOF
	fi

	cat <<- EOF >> settings.json
	}
	EOF
fi

cat settings.json
echo "Installing plugins..."
if [ $ETHERPAD_PLUGINS ]; then
	IFS=',' read -r -a PLUGIN_LIST <<< "$ETHERPAD_PLUGINS"
	for PLUGIN in "${PLUGIN_LIST[@]}"
	do
	    ./src/node_modules/.bin/npm install ${PLUGIN}
	done
fi

exec "$@"
