#!/usr/bin/env bash
#
# Fedora-native replacement for posthog/bin/upgrade-hobby.
#
# Upstream's script is unusable here: it calls apt-get, re-downloads the v1
# `docker-compose` binary, and overwrites compose.yml from the repo (throwing
# away this server's nginx-proxy-manager and port changes). This does the same
# work using dnf-era tooling and replays the local patches afterwards.
#
set -euo pipefail
cd "$(dirname "$0")/.."

echo "==> Refreshing the PostHog checkout"
git -C posthog fetch origin
git -C posthog reset --hard origin/master
echo "    now on $(git -C posthog rev-parse --short HEAD)"

echo "==> Refreshing compose files and re-applying local patches"
cp posthog/docker-compose.base.yml docker-compose.base.yml
cp posthog/docker-compose.hobby.yml compose.yml
cp posthog/.env.services .env.services
bin/apply-local-patches.py compose.yml
docker compose config >/dev/null && echo "    compose config OK"

echo "==> Refreshing the GeoIP database"
curl -sL 'https://mmdbcdn.posthog.net/' --http1.1 | brotli --decompress > share/GeoLite2-City.mmdb
echo "{\"date\": \"$(date +%F)\"}" > share/GeoLite2-City.json
chmod 644 share/GeoLite2-City.mmdb share/GeoLite2-City.json

echo "==> Pulling images"
docker compose pull

echo "==> Checking async migrations against the new version"
docker compose up -d db redis7 clickhouse
docker compose run --rm asyncmigrationscheck

echo "==> Restarting the stack"
docker compose up -d --remove-orphans

# web, worker and temporal-django-worker apply compose/local-patches.py on start.
# Surface the result so an upstream change that breaks a patch is not missed.
echo "==> Local source patches"
sleep 15
docker compose logs --since 5m web worker temporal-django-worker 2>&1 | grep LOCAL-PATCH || \
    echo "    no LOCAL-PATCH lines yet, check: docker compose logs web worker | grep LOCAL-PATCH"

echo
echo "Done. Watch the migrations with:  docker compose logs -f web"
