#!/bin/sh
# Wait for the database, make sure moodledata is writable, then run whatever was asked for.
set -e

host="${MOODLE_DB_HOST:-db}"
port="${MOODLE_DB_PORT:-5432}"
printf 'waiting for %s:%s ' "$host" "$port"
for i in $(seq 1 60); do
  if php -r "exit(@fsockopen(getenv('MOODLE_DB_HOST') ?: 'db', (int)(getenv('MOODLE_DB_PORT') ?: 5432)) ? 0 : 1);"; then
    echo "· up"
    break
  fi
  printf '.'
  sleep 2
done

mkdir -p "${MOODLE_DATAROOT:-/var/www/moodledata}"
chown -R www-data:www-data "${MOODLE_DATAROOT:-/var/www/moodledata}" 2>/dev/null || true

# Thinkera's plugins, in every container built from this image (see sync-plugins.sh)
sync-plugins

# nginx serves Moodle's static files from a shared volume; refresh it on every start so a rebuilt
# image never leaves stale code behind (the classic shared-volume trap).
if [ -n "${MOODLE_CODE_SHARE:-}" ] && [ -d "${MOODLE_CODE_SHARE}" ]; then
  rsync -a --delete --exclude 'config.php' /var/www/html/ "${MOODLE_CODE_SHARE}/"
  echo "code synced to ${MOODLE_CODE_SHARE}"
fi

exec "$@"
