#!/bin/bash
set -e

cd /var/www/znik.org/clearfinch

git pull origin main
npm ci
npm run build:standalone   # build + copy static/, public/ and .env.local into .next/standalone
sudo systemctl restart clearfinch

# 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 to come up …"
for _ in $(seq 1 20); do
  sleep 1
  curl -fsS http://127.0.0.1:3001/clearfintest/api/health/mail >/dev/null 2>&1 && break
done

if ! curl -fsS http://127.0.0.1:3001/clearfintest/api/health/mail; then
  echo
  echo "DEPLOY FAILED: /api/health/mail reports the contact form is not configured."
  echo "Check /var/www/znik.org/clearfinch/.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."
