#!/bin/sh
set -eu

# One-time host permission setup for the file-based Rspamd DKIM integration.
# The web service stays unprivileged; both daemons share only this dedicated group.

KEY_DIR="${POSTFIXADMIN_RS_RSPAMD_KEY_DIR:-/var/lib/rspamd/dkim}"
SIGNING_CONFIG="${POSTFIXADMIN_RS_RSPAMD_SIGNING_CONFIG:-/etc/rspamd/local.d/dkim_signing.conf}"
SHARED_GROUP="${POSTFIXADMIN_RS_RSPAMD_GROUP:-postfixadmin-rspamd}"

if [ "$(id -u)" -ne 0 ]; then
  echo "error: run this helper as root" >&2
  exit 1
fi

if ! getent passwd postfixadmin >/dev/null 2>&1; then
  echo "error: postfixadmin service user does not exist; install postfixadmin-rs first" >&2
  exit 1
fi

RSPAMD_USER="${POSTFIXADMIN_RS_RSPAMD_USER:-}"
if [ -z "$RSPAMD_USER" ]; then
  for candidate in _rspamd rspamd; do
    if getent passwd "$candidate" >/dev/null 2>&1; then
      RSPAMD_USER="$candidate"
      break
    fi
  done
fi
if [ -z "$RSPAMD_USER" ] || ! getent passwd "$RSPAMD_USER" >/dev/null 2>&1; then
  echo "error: cannot determine Rspamd runtime user; set POSTFIXADMIN_RS_RSPAMD_USER" >&2
  exit 1
fi

if ! getent group "$SHARED_GROUP" >/dev/null 2>&1; then
  addgroup --system "$SHARED_GROUP" >/dev/null
fi

usermod -a -G "$SHARED_GROUP" postfixadmin
usermod -a -G "$SHARED_GROUP" "$RSPAMD_USER"

# The root DKIM directory is writable by the shared group. Domain directories
# created by PostfixAdmin-RS inherit the group through setgid.
install -d -o root -g "$SHARED_GROUP" -m 2770 "$KEY_DIR"

# Normalize already-managed domain directories and files without making private
# keys world-readable. The service owns subdirectories so it can rotate keys.
find "$KEY_DIR" -mindepth 1 -type d -exec chown postfixadmin:"$SHARED_GROUP" {} \; -exec chmod 2750 {} \;
find "$KEY_DIR" -type f -exec chgrp "$SHARED_GROUP" {} \;
find "$KEY_DIR" -type f -name '*.private' -exec chmod 0640 {} \;
find "$KEY_DIR" -type f ! -name '*.private' -exec chmod 0640 {} \;

# PostfixAdmin-RS edits this single Rspamd config file directly. Creating it here
# avoids granting write access to the whole /etc/rspamd/local.d directory.
SIGNING_DIR="$(dirname "$SIGNING_CONFIG")"
if [ ! -d "$SIGNING_DIR" ]; then
  install -d -o root -g root -m 0755 "$SIGNING_DIR"
fi
if [ ! -e "$SIGNING_CONFIG" ]; then
  : > "$SIGNING_CONFIG"
fi
chown root:"$SHARED_GROUP" "$SIGNING_CONFIG"
chmod 0660 "$SIGNING_CONFIG"

cat <<MSG
Rspamd DKIM permissions prepared.
  Rspamd user:     $RSPAMD_USER
  Shared group:    $SHARED_GROUP
  Key directory:   $KEY_DIR
  Signing config:  $SIGNING_CONFIG

Restart both services so supplementary groups are reloaded:
  systemctl restart postfixadmin-rs rspamd
MSG
