#!/bin/bash
#
# Move every credential out of .env and into the database.
#
# After this runs, .env holds four values and none of them is an API key. The
# reason is the 21 August 2026 Stripe alert: a live secret key was used from an
# address that was not ours, and .env was the only place that key existed
# outside Stripe. A file on disk travels into backups, into synced folders and
# into every copy of the tree. The database keeps these encrypted at rest and
# only the panel can edit them.
#
# Order matters, for the same reason it mattered on 21 August. Two fields are
# being added to SiteSettings. Django puts every model field into the SELECT
# for every query on that table, so if models.py lands before the migration,
# PostgreSQL rejects every Settings read and the site goes down. Migration
# first, confirmed applied, then the code.
#
# Usage, from the Mac:
#   bash deploy/ship-db-only-credentials.sh
#
set -euo pipefail

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

MIGRATIONS="apps/pages/migrations/0034_sitesettings_support_mailbox.py
apps/pages/migrations/0035_sitesettings_recaptcha_v2.py"

CODE="apps/pages/models.py
apps/pages/api_keys.py
apps/pages/email_backend.py
apps/pages/sms_utils.py
apps/pages/whatsapp_utils.py
apps/ecommerce/stripe_utils.py
apps/ecommerce/views.py
apps/ecommerce/auction_views.py
apps/ecommerce/deal_views.py
apps/ecommerce/email_utils.py
apps/auction/views.py
apps/contact/views.py
apps/accounts/views.py
apps/accounts/twofa.py
apps/accounts/cms_views.py
apps/chat/openai_client.py
apps/tickets/management/commands/fetch_ticket_replies.py
config/settings/base.py
config/settings/production.py
templates/cms/settings.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 pages --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 pages --settings=config.settings.production | tail -4"
read -r -p "Both 0034 and 0035 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 ──────────────────────────────────────────────────────────"
ssh "$SERVER" "systemctl restart finaltarget && sleep 2 && systemctl is-active finaltarget"

echo
echo "── 5. What the code can still see ──────────────────────────────────────"
# Every one of these should print a value read from the database. A blank here
# means the key was never typed into Settings, and .env must not be stripped
# until it is.
ssh "$SERVER" "cd ${REMOTE} && venv/bin/python manage.py shell --settings=config.settings.production -c \"
from apps.pages import api_keys as K
from apps.pages.email_backend import outgoing_address, support_credentials
from apps.ecommerce.stripe_utils import _get_stripe_secret_key, _get_stripe_webhook_secret
def mask(v): return (v[:7] + '…' + v[-4:]) if len(v) > 14 else ('set' if v else 'BLANK')
print('  no-reply        ', outgoing_address() or 'BLANK')
print('  support mailbox ', support_credentials()[0] or 'BLANK', '/ password', mask(support_credentials()[1]))
print('  stripe secret   ', mask(_get_stripe_secret_key()))
print('  stripe webhook  ', mask(_get_stripe_webhook_secret()))
print('  stripe public   ', mask(K.get_stripe_public_key()))
print('  openai          ', mask(K.get_openai_api_key()))
print('  recaptcha v3    ', mask(K.get_recaptcha_site_key()), '/', mask(K.get_recaptcha_secret_key()))
print('  recaptcha v2    ', mask(K.get_recaptcha_v2_site_key()), '/', mask(K.get_recaptcha_v2_secret_key()))
print('  twilio          ', [mask(x) for x in K.get_twilio_credentials()])
\""

echo
echo "Nothing has been removed from .env yet. Read the list above first."
echo "Anything showing BLANK is not in Settings, so do not delete its .env line."
