#!/bin/sh

# Checks if Plume has already been launched one
# Otherwise, initialize the instance and create
# a file at FIRSTLAUNCH_PATH to indicate that the
# instance has already been initialized
# FIRSTLAUNCH_PATH is configured via environment
#
# Also manage running migrations when updating

if [ -z "${POSTGRES_PASSWORD}" ]; then
	echo >&2 'Error : missing required ${POSTGRES_PASSWORD} environment variable, exiting.'
	exit 1
fi
if [ -z "${POSTGRES_USER}" ]; then
	echo >&2 'Error : missing required ${POSTGRES_USER} environment variable, exiting.'
	exit 1
fi
if [ -z "${POSTGRES_DB}" ]; then
	echo >&2 'Error : missing required ${POSTGRES_DB} environment variable, exiting.'
	exit 1
fi


# Wait for database to be ready
while ! PGPASSWORD="${POSTGRES_PASSWORD}" psql -h"${DB_HOST}" -U"${POSTGRES_USER}" -d"${POSTGRES_DB}" -c "SELECT 1" &>/dev/null; do
  echo "Database server not ready yet, re-trying in 5 seconds..."
  sleep 5
done

# If first launch, initialize and create marker file
if [ ! -f ${FIRSTLAUNCH_PATH} ]; then
  echo "First launch detected."
  echo "Initialize search index..."
  plume plm search init
  echo "Initialize instance..."
  plume plm instance new -d '$URL' -n '$NAME' -l 'CC-BY-SA'
  echo "Create admin user..."
  plume plm users new -n '$ADMIN_USER' -N '$ADMIN_NAME' -b '' -e '$ADMIN_EMAIL' -p '$ADMIN_PASS' --admin
  echo "Done."
  touch ${FIRSTLAUNCH_PATH}
fi

# Check if we updated since last launch
if [ ${PLUME_VERSION} != $(cat ${FIRSTLAUNCH_PATH}) ]; then
   # If so, we need to run migrations
   echo "Instance updated since last launch, running migrations..."
   plume plm migration run
fi

# Now write the version if the file
echo "${PLUME_VERSION}" > ${FIRSTLAUNCH_PATH}
echo "Launching Plume..."