#!/bin/bash
# Pre-upgrade hook for the house `upgrade` flow (installed at
# /federated/services/superbrain/upgrade/pre by install.sh / update.sh).
#
# Args (house convention): $1 = old version, $2 = new version.
#
# Two jobs:
#   1. Consistent pre-upgrade database backup (listmonk house pattern —
#      the btrfs snapshot upgrade_app takes covers files, but a live dump
#      is the restorable artifact). Last 5 kept under the app dir.
#   2. upgrade_app pulls only CONTAINER (the app image) before redeploying;
#      superbrain is THREE images sharing one tag, so pull web + migrate at
#      the target version too. Compose interpolates ${IMAGE_VERSION} from
#      .env (still the old version at this point) — the shell environment
#      wins over .env, so pin it explicitly.
set -euo pipefail

OLD="${1:-unknown}"
NEW="${2:?usage: pre <old-version> <new-version>}"
cd /federated/apps/superbrain

mkdir -p .update-backups && chmod 700 .update-backups
DUMP=".update-backups/pre-upgrade-$OLD-to-$NEW-$(date +%Y%m%d-%H%M%S).sql.gz"
echo "* Backing up the superbrain database to $DUMP"
docker exec postgresql /bin/bash -c "pg_dump superbrain -U postgres -c" | gzip > "$DUMP"
ls -1t .update-backups/pre-upgrade-*.sql.gz 2>/dev/null | tail -n +6 | xargs -r rm -f

echo "* Pulling superbrain images at $NEW"
IMAGE_VERSION="$NEW" docker compose pull app web migrate
