#!/bin/bash
# =================================================================
# set-relay-credentials.sh — Configura credenciales Brevo en Postfix
# Uso: sudo bash /var/www/resetea.net/infra/set-relay-credentials.sh LOGIN SMTP_KEY
#
# LOGIN    = email con que te registraste en Brevo
# SMTP_KEY = clave SMTP de Brevo (SMTP & API → SMTP → Generate key)
# =================================================================

if [[ $EUID -ne 0 ]]; then
  echo "ERROR: Ejecuta como root: sudo bash $0 LOGIN SMTP_KEY"
  exit 1
fi

if [[ -z "$1" || -z "$2" ]]; then
  echo "Uso: sudo bash $0 LOGIN SMTP_KEY"
  echo "Ejemplo: sudo bash $0 user@email.com xsmtpsib-abc123..."
  exit 1
fi

LOGIN="$1"
SMTP_KEY="$2"

echo "[smtp-relay.brevo.com]:587  ${LOGIN}:${SMTP_KEY}" > /etc/postfix/sasl_passwd
chmod 600 /etc/postfix/sasl_passwd
postmap /etc/postfix/sasl_passwd
echo "  → sasl_passwd actualizado"

systemctl restart postfix
echo "  → Postfix arrancado"

# Test de envío
echo ""
echo "Haciendo test de envío..."
echo "Test resetea.net SMTP relay $(date)" | sendmail -v -f privacy@resetea.net privacy@resetea.net 2>&1 | head -10

echo ""
echo "Verifica el log: sudo journalctl -u postfix -n 20"
echo "O el log de mail: sudo tail -20 /var/log/mail.log"
