#!/bin/sh
# Take the site's content off this machine: the CMS database and the images uploaded through it.
# The seed files only build a brand-new site; everything edited since lives in the database.
#
#   cd thinkera.academy && sh ../deploy/export-site.sh
#
# It writes deploy/_export/<date>/ : site-db.dump, site-media.tgz, SHA256SUMS.
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 POSTGRES_USER)
db_name=$(envval POSTGRES_DB)
[ -n "$db_user" ] && [ -n "$db_name" ] || { echo "run this from thinkera.academy (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/site-db.dump"

echo "media …"
docker compose exec -T web tar czf - -C /app/media . > "$out/site-media.tgz"

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 site-db.dump -e site-media.tgz "$out/SHA256SUMS" > "$out/SHA256SUMS.keep" || :
fi
( cd "$out" && sha256sum site-db.dump site-media.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 content»"
