#!/bin/bash
# =================================================================
# setup-mail.sh — Postfix (relay Brevo) + opendkim para resetea.net
# Uso: sudo bash /var/www/resetea.net/infra/setup-mail.sh
# =================================================================
set -e

DOMAIN="resetea.net"
SELECTOR="mail"
DKIM_DIR="/etc/opendkim/keys/${DOMAIN}"
NODE_BIN="/home/capitansito/.nvm/versions/node/v18.20.8/bin/node"
APP_DIR="/var/www/resetea.net/api"
APP_USER="capitansito"

# ── Verificaciones previas ────────────────────────────────────────
if [[ $EUID -ne 0 ]]; then
  echo "ERROR: Ejecuta como root: sudo bash $0"
  exit 1
fi

if [[ ! -f "${NODE_BIN}" ]]; then
  echo "ERROR: node no encontrado en ${NODE_BIN}"
  echo "Ajusta NODE_BIN al inicio del script."
  exit 1
fi

echo ""
echo "╔══════════════════════════════════════════════╗"
echo "║  SETUP MAIL — resetea.net                    ║"
echo "╚══════════════════════════════════════════════╝"

# ── [1/6] Instalar paquetes ───────────────────────────────────────
echo ""
echo "[1/6] Instalando postfix, opendkim, opendkim-tools..."
DEBIAN_FRONTEND=noninteractive apt-get install -y \
  postfix libsasl2-modules opendkim opendkim-tools

# ── [2/6] Configurar Postfix ──────────────────────────────────────
echo ""
echo "[2/6] Configurando Postfix..."

postconf -e "myhostname = ${DOMAIN}"
postconf -e "myorigin = ${DOMAIN}"
postconf -e "inet_interfaces = loopback-only"
postconf -e "mydestination = localhost"
postconf -e "mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128"

# Relay Brevo — credenciales se añaden con set-relay-credentials.sh
postconf -e "relayhost = [smtp-relay.brevo.com]:587"
postconf -e "smtp_sasl_auth_enable = yes"
postconf -e "smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd"
postconf -e "smtp_sasl_security_options = noanonymous"
postconf -e "smtp_tls_security_level = encrypt"
postconf -e "smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt"
postconf -e "smtp_use_tls = yes"

# Integración opendkim via milter
postconf -e "milter_protocol = 6"
postconf -e "milter_default_action = accept"
postconf -e "smtpd_milters = inet:localhost:12301"
postconf -e "non_smtpd_milters = inet:localhost:12301"

# Placeholder de credenciales (vacío hasta ejecutar set-relay-credentials.sh)
if [[ ! -f /etc/postfix/sasl_passwd ]]; then
  echo "[smtp-relay.brevo.com]:587  BREVO_LOGIN:BREVO_SMTP_KEY" > /etc/postfix/sasl_passwd
  chmod 600 /etc/postfix/sasl_passwd
  postmap /etc/postfix/sasl_passwd
fi

# ── [3/6] Generar claves DKIM ─────────────────────────────────────
echo ""
echo "[3/6] Generando claves DKIM (2048 bits)..."

mkdir -p "${DKIM_DIR}"

if [[ -f "${DKIM_DIR}/${SELECTOR}.private" ]]; then
  echo "  → Clave ya existente, se mantiene (no se regenera)."
else
  opendkim-genkey -b 2048 -d "${DOMAIN}" -D "${DKIM_DIR}" -s "${SELECTOR}" -v
  echo "  → Clave generada en ${DKIM_DIR}/"
fi

chown -R opendkim:opendkim /etc/opendkim/
chmod 711 "${DKIM_DIR}"           # traversable pero no listable por otros
chmod 600 "${DKIM_DIR}/${SELECTOR}.private"
chmod 644 "${DKIM_DIR}/${SELECTOR}.txt"  # clave pública — legible por el script

# ── [4/6] Configurar opendkim ─────────────────────────────────────
echo ""
echo "[4/6] Configurando opendkim..."

cat > /etc/opendkim.conf << EOF
AutoRestart         Yes
AutoRestartRate     10/1h
UMask               002
Syslog              yes
SyslogSuccess       Yes
LogWhy              Yes
Canonicalization    relaxed/simple
ExternalIgnoreList  refile:/etc/opendkim/TrustedHosts
InternalHosts       refile:/etc/opendkim/TrustedHosts
KeyTable            refile:/etc/opendkim/KeyTable
SigningTable        refile:/etc/opendkim/SigningTable
Mode                sv
PidFile             /run/opendkim/opendkim.pid
SignatureAlgorithm  rsa-sha256
UserID              opendkim
Socket              inet:12301@localhost
EOF

cat > /etc/opendkim/TrustedHosts << EOF
127.0.0.1
localhost
${DOMAIN}
EOF

cat > /etc/opendkim/KeyTable << EOF
${SELECTOR}._domainkey.${DOMAIN}  ${DOMAIN}:${SELECTOR}:${DKIM_DIR}/${SELECTOR}.private
EOF

cat > /etc/opendkim/SigningTable << EOF
*@${DOMAIN}  ${SELECTOR}._domainkey.${DOMAIN}
EOF

# ── [5/6] Servicio systemd para resetea backend ───────────────────
echo ""
echo "[5/6] Creando servicio systemd resetea..."

cat > /etc/systemd/system/resetea.service << EOF
[Unit]
Description=RESETEA.NET backend Node.js
After=network.target

[Service]
Type=simple
User=${APP_USER}
WorkingDirectory=${APP_DIR}
ExecStart=${NODE_BIN} app.js
Restart=on-failure
RestartSec=5
EnvironmentFile=${APP_DIR}/.env

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable resetea
systemctl start resetea && echo "  → resetea backend arrancado" || echo "  ⚠ Error arrancando resetea — revisa: journalctl -u resetea -n 20"

# ── [6/6] Arrancar opendkim y postfix ─────────────────────────────
echo ""
echo "[6/6] Arrancando opendkim y postfix..."

systemctl enable opendkim
systemctl restart opendkim && echo "  → opendkim OK" || echo "  ⚠ Error en opendkim"
sleep 1

# Postfix NO se arranca hasta que haya credenciales reales en sasl_passwd
echo "  → Postfix: esperando credenciales Brevo antes de arrancar."
echo "     Ejecuta set-relay-credentials.sh cuando tengas las credenciales."

# ── Resumen final ─────────────────────────────────────────────────
echo ""
echo "════════════════════════════════════════════════════════"
echo "  REGISTRO DKIM — añadir en DNS de Gandi:"
echo "────────────────────────────────────────────────────────"
echo "  Nombre:  ${SELECTOR}._domainkey"
echo "  Tipo:    TXT"
DKIM_P=$(cat "${DKIM_DIR}/${SELECTOR}.txt" | grep -o '"p=.*"' | tr -d '"' | tr -d ' ')
echo "  Valor:   v=DKIM1; k=rsa; ${DKIM_P}"
echo ""
echo "  (archivo completo en ${DKIM_DIR}/${SELECTOR}.txt)"
echo "════════════════════════════════════════════════════════"
echo ""
echo "SIGUIENTE PASO:"
echo "  1. Crea cuenta gratis en https://app.brevo.com"
echo "  2. Ve a: SMTP & API → SMTP → 'Generate a new SMTP Key'"
echo "  3. Ejecuta:"
echo "     sudo bash /var/www/resetea.net/infra/set-relay-credentials.sh TU_EMAIL_BREVO TU_SMTP_KEY"
echo "  4. Añade el registro DKIM de arriba en Gandi"
echo "  5. Ejecuta el managedns.sh setup-mail-dns para SPF y DMARC"
echo ""
