#!/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

# The web container only (it is the one with MOODLE_CODE_SHARE): session locks held by the requests of the container
# this one replaces died with it, but Redis keeps them, and each would lock its user out until it expires.
if [ -n "${MOODLE_CODE_SHARE:-}" ] && [ -n "${MOODLE_REDIS_HOST:-}" ]; then
  php -r '
    $r = new Redis();
    if (!@$r->connect(getenv("MOODLE_REDIS_HOST"), (int) (getenv("MOODLE_REDIS_PORT") ?: 6379), 5)) { exit(0); }
    $r->select((int) (getenv("MOODLE_REDIS_DB") ?: 0));
    $pattern = (getenv("MOODLE_REDIS_PREFIX") ?: "mdl_sess_") . "*.lock";
    $n = 0; $it = null;
    while (($keys = $r->scan($it, $pattern, 500)) !== false) { if ($keys) { $n += $r->del($keys); } if (!$it) { break; } }
    echo "session locks of the previous container cleared: $n\n";
  ' || true
fi

# 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 "$@"
