#!/bin/sh
# Take everything the platform holds off this machine: the database and moodledata (uploads, the file store,
# the generated language overrides). Run it where the platform is working — it only reads.
#
#   cd platform/moodle && sh ../../deploy/export-platform.sh
#
# It writes deploy/_export/<date>/ : moodle-db.dump, moodledata.tgz, and the checksums to compare after the copy.
set -e

# Git Bash on Windows rewrites a container path like /app/media into a path on the C: drive
# before docker ever sees it. Linux has no such habit, so this is harmless on the server.
MSYS_NO_PATHCONV=1
export MSYS_NO_PATHCONV

# A value from .env. Windows line endings travel with the file, and a trailing carriage return turns
# «moodle» into a name Postgres has never heard of, so it is stripped here once.
envval() {
    grep "^$1=" .env | head -1 | cut -d= -f2- | tr -d '\015'
}

here=$(cd "$(dirname "$0")" && pwd)
# EXPORT_DIR lets a caller say where this should land; without it, the dated folder under _export.
out=${EXPORT_DIR:-$here/_export/$(date +%Y-%m-%d)}
mkdir -p "$out"

db_user=$(envval MOODLE_DB_USER)
db_name=$(envval MOODLE_DB_NAME)
[ -n "$db_user" ] && [ -n "$db_name" ] || { echo "run this from platform/moodle (its .env is read here)"; exit 1; }

echo "database ($db_name) …"
docker compose exec -T db pg_dump -U "$db_user" -d "$db_name" -Fc > "$out/moodle-db.dump"

echo "moodledata …"
docker compose exec -T moodle tar czf - -C /var/www/moodledata . > "$out/moodledata.tgz"

# the videos the lessons no longer use (they are YouTube links now) are the bulk of it; this lists them so the
# copy can be judged, but nothing is deleted here
echo "checksums …"
# Only this export's own two lines are rewritten; whatever the other export left stays,
# so one list covers the whole folder whichever export ran last.
if [ -f "$out/SHA256SUMS" ]; then
    grep -v -e moodle-db.dump -e moodledata.tgz "$out/SHA256SUMS" > "$out/SHA256SUMS.keep" || :
fi
( cd "$out" && sha256sum moodle-db.dump moodledata.tgz >> SHA256SUMS.keep )
mv "$out/SHA256SUMS.keep" "$out/SHA256SUMS"

ls -lh "$out"
echo
echo "copy the folder to the server, then follow deploy/README.md → «Moving the platform's content»"
