#!/usr/bin/env bash
# Setzt Postfix myhostname/myorigin und bereinigt /etc/aliases.
# Wird von Mailwolt aufgerufen wenn die Mail-Domain gespeichert wird.
set -euo pipefail

MAIL_HOST="${1:-}"
if [ -z "${MAIL_HOST}" ]; then
  echo "Usage: mailwolt-apply-hostname <mail-host>" >&2
  exit 1
fi

# Nur sichere Hostnamen zulassen
if ! echo "${MAIL_HOST}" | grep -qE '^[a-zA-Z0-9][a-zA-Z0-9.\-]+$'; then
  echo "Ungültiger Hostname: ${MAIL_HOST}" >&2
  exit 1
fi

if command -v postconf >/dev/null 2>&1; then
  postconf -e "myhostname = ${MAIL_HOST}"
  postconf -e "myorigin = ${MAIL_HOST}"
  postconf -e "mydestination = ${MAIL_HOST}, localhost.localdomain, localhost"
  systemctl reload postfix 2>/dev/null || true
fi

if [ -f /etc/aliases ]; then
  if grep -q '^root:' /etc/aliases; then
    sed -i 's|^root:.*|root: /dev/null|' /etc/aliases
  else
    echo 'root: /dev/null' >> /etc/aliases
  fi
  if grep -q '^clamav:' /etc/aliases; then
    sed -i 's|^clamav:.*|clamav: /dev/null|' /etc/aliases
  else
    echo 'clamav: /dev/null' >> /etc/aliases
  fi
  command -v newaliases >/dev/null 2>&1 && newaliases
fi

echo "mailwolt-apply-hostname fertig"
