#!/bin/bash

set -e

. "${INSTALLER_DIR}/wizard"

CONF_FILE="/etc/${APP_NAME}/conf.d/00_addon_postgres"

function generate_database_template() {
	PGPASSWORD="$(wiz_get "postgres/db_password")"
	PGHOST="$(wiz_get "postgres/db_host")"
	PGPORT="$(wiz_get "postgres/db_port")"
	PGUSER="$(wiz_get "postgres/db_username")"
	PGDATABASE="$(wiz_get "postgres/db_name")"

	local encoded_password="$(wiz_urlencode "$PGPASSWORD")"

	echo "export DATABASE_URL=\"postgres://${PGUSER}:${encoded_password}@${PGHOST}:${PGPORT}/${PGDATABASE}\"" > "$CONF_FILE"
	chown "${APP_USER}.${APP_GROUP}" "$CONF_FILE"
}

case "$(wiz_get "postgres/autoinstall")" in
	"reuse")
		generate_database_template
		;;
	"install")
		generate_database_template
		;;
	*)
		;;
esac

exit 0
