#!/bin/bash
#
# Ship 26.8.5 to Final Target.
#
# The order matters and is the whole point of this script. On 21 August 2026 a
# model and its migration went out together, PostgreSQL rejected every Tenant
# query in the gap, and the public site and the panel both went down. So:
# migrations first, confirmed applied, then the code that depends on them.
#
# Usage, from the Mac:
#   bash deploy/ship-26.8.5.sh
#
set -euo pipefail

SERVER="root@194.76.26.170"
REMOTE="/home/finaltarget/public_html/backend"
LOCAL="$(cd "$(dirname "$0")/.." && pwd)"

MIGRATIONS="apps/tenants/migrations/0021_invoice_payment_link.py apps/ftlink/migrations/0004_jobrun.py"

CODE="config/settings/base.py config/urls.py
apps/accounts/cms_views.py apps/accounts/context_processors.py
apps/tenants/models.py apps/tenants/renewal_views.py
apps/tenants/management/commands/send_renewal_warnings.py
apps/tickets/models.py apps/tickets/management/commands/fetch_ticket_replies.py
apps/ftlink/models.py apps/ecommerce/views.py
templates/cms/system_info.html templates/cms/dashboard.html
templates/cms/tenants/billing.html
templates/public/renew.html templates/public/emails/renewal_warning.html"

echo "── 1. Migrations first, on their own ───────────────────────────────────"
cd "$LOCAL"
rsync -av --relative $MIGRATIONS "${SERVER}:${REMOTE}/"
ssh "$SERVER" "cd ${REMOTE} && venv/bin/python manage.py migrate --settings=config.settings.production"

echo
echo "── 2. Confirm they applied before any code that reads them ─────────────"
ssh "$SERVER" "cd ${REMOTE} && venv/bin/python manage.py showmigrations tenants ftlink --settings=config.settings.production | grep -E '0021_invoice_payment_link|0004_jobrun'"
read -r -p "Both marked [X]? Continue with the code? [y/N] " reply
[ "$reply" = "y" ] || [ "$reply" = "Y" ] || { echo "Stopped. Nothing else sent."; exit 1; }

echo
echo "── 3. Code ─────────────────────────────────────────────────────────────"
rsync -av --relative $CODE "${SERVER}:${REMOTE}/"

echo
echo "── 4. Restart and check ────────────────────────────────────────────────"
ssh "$SERVER" "systemctl restart finaltarget && sleep 2 && systemctl is-active finaltarget"
ssh "$SERVER" "cd ${REMOTE} && venv/bin/python manage.py send_renewal_warnings --dry-run --settings=config.settings.production"

echo
echo "Done. Check https://panel.finaltarget.com/system/ reads v26.8.5."
echo "If the page looks stale, purge the Cloudflare cache for the panel host."
