#!/bin/bash
set -e

cd /var/www/clearfin.ch/app

git pull origin prod
npm ci
# Empty basePath so the site serves at the domain root, not /clearfintest.
NEXT_PUBLIC_BASE_PATH='' npm run build:standalone
sudo systemctl restart clearfinch-prod

# Fail the deploy if the running server cannot see its SMTP settings, rather
# than letting the contact form 500 for visitors until someone notices.
echo "Waiting for clearfinch-prod to come up …"
for _ in $(seq 1 20); do
  sleep 1
  curl -fsS http://127.0.0.1:3000/api/health/mail >/dev/null 2>&1 && break
done

if ! curl -fsS http://127.0.0.1:3000/api/health/mail; then
  echo
  echo "DEPLOY FAILED: /api/health/mail reports the contact form is not configured."
  echo "Check /var/www/clearfin.ch/app/.env.local: it needs SMTP_FROM and CONTACT_TO, plus"
  echo "MAIL_TRANSPORT=sendmail (and a working msmtp at /usr/sbin/sendmail)."
  echo "The response above names what is missing."
  exit 1
fi

echo
echo "Deploy complete."
