#!/bin/sh
# Copy Thinkera's plugins from the read-only mount (/opt/thinkera-plugins) into Moodle's code tree.
#
# Every container built from this image (moodle and cron) runs this at start, so they all see the same plugins.
# They share one component cache in moodledata: a container without the plugins would rebuild that cache without
# them, and every page would fail with "Invalid component used in plugin/component_callback(): theme_thinkera".
# Copying (instead of mounting the plugins in place) also keeps OneDrive sync hiccups out of Moodle's reads.
#
# After editing a plugin:  docker compose exec moodle sync-plugins   (copies, refreshes nginx's copy, purges caches)
set -e
SRC=/opt/thinkera-plugins
CODE=/var/www/html/public
[ -d "$SRC" ] || { echo "sync-plugins: $SRC is not mounted, nothing to do"; exit 0; }

copy() {  # copy <source folder under plugins/> <target folder under public/>
  if [ -f "$SRC/$1/version.php" ]; then   # a folder with no version.php is not a plugin yet
    mkdir -p "$CODE/$2"
    rsync -a --delete "$SRC/$1/" "$CODE/$2/"
    chown -R www-data:www-data "$CODE/$2"
    echo "  $1 -> public/$2"
  fi
}
copy theme/thinkera        theme/thinkera
copy filter/tkvideo        filter/tkvideo
copy format/thinkera       course/format/thinkera
copy availability/tkpaid   availability/condition/tkpaid
copy enrol/instapay        enrol/instapay
copy local/thinkera        local/thinkera
copy local/wagateway       local/wagateway
copy message/whatsapp      message/output/whatsapp

# Run by hand (not at start): refresh nginx's copy of the code and rebuild the caches.
if [ "${1:-}" = "--live" ]; then
  if [ -n "${MOODLE_CODE_SHARE:-}" ] && [ -d "${MOODLE_CODE_SHARE}" ]; then
    rsync -a --delete --exclude 'config.php' /var/www/html/ "${MOODLE_CODE_SHARE}/"
  fi
  su -s /bin/sh www-data -c "php /var/www/html/admin/cli/purge_caches.php"
  # opcache re-reads changed files only every 60 s: a graceful php-fpm reload makes the new code live at once
  kill -USR2 1 2>/dev/null && echo "php-fpm reloaded"
  echo "caches purged"
fi
