#!/usr/bin/env bash
#
# onx-exim-sasl-enable — Exim için Dovecot SASL socket erişimi
#
# v83.15: Exim daemon 587 submission port'unda Dovecot SASL auth kullanır
# (dovecot_login + dovecot_plain authenticators). Default Dovecot auth-client
# socket mode=0600 user=dovecot → Exim user "Permission denied" alır.
#
# Bu script /etc/dovecot/conf.d/99-onx-exim-sasl.conf oluşturur:
#   service auth { unix_listener auth-client { mode=0660 group=exim ... } }
#
# Idempotent — script tekrar çalışırsa dosya yeniden yazılır + Dovecot reload.
# Postfix bu socket'i kullanmaz (Postfix kendi SASL config'i ile çalışır), bu
# yüzden Postfix aktifken bile config kalsa zararı yok.
#
# Output: {"ok":true,"socket":"...","mode":"0660","group":"exim"}

set -uo pipefail
SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"
source "${SCRIPT_DIR}/_lib/common.sh"

require_root
require_cmd doveconf
require_cmd systemctl

DROPIN="/etc/dovecot/conf.d/99-onx-exim-sasl.conf"
SOCKET="/var/run/dovecot/auth-client"

# Exim user/group var mi?
if ! getent passwd exim >/dev/null 2>&1; then
    onx_die 2 "exim user yok (Exim kurulu degil)"
fi

# Config yaz (idempotent — her seferinde overwrite, icerik ayni)
cat > "$DROPIN" <<'EOF'
# v83.15: Exim SASL auth — Dovecot auth-client unix socket'i exim grubuna ac.
# Default mode=0600 user=dovecot → Exim "Permission denied" aliyor.
# group=exim + mode=0660 ile Exim auth socket'e baglanabilir.
# Postfix bu socket'i kullanmaz (Postfix Dovecot'a TCP/inet veya kendi SASL ile baglanir).
service auth {
  unix_listener auth-client {
    mode = 0660
    user = dovecot
    group = exim
  }
}
EOF
chmod 0644 "$DROPIN"

# Syntax check
if ! doveconf -n >/dev/null 2>&1; then
    rm -f "$DROPIN"
    onx_die 3 "doveconf syntax check basarisiz — config rollback"
fi

# Reload Dovecot
systemctl reload dovecot 2>/dev/null || systemctl restart dovecot
sleep 1

# Verify socket permissions
if [[ ! -S "$SOCKET" ]]; then
    onx_die 3 "Socket olusmadi: $SOCKET (dovecot baslatilamadi?)"
fi

SOCKET_GROUP=$(stat -c '%G' "$SOCKET")
SOCKET_MODE=$(stat -c '%a' "$SOCKET")

# Exim user gercekten erisebiliyor mu?
EXIM_CAN_READ="false"
sudo -u exim test -r "$SOCKET" 2>/dev/null && EXIM_CAN_READ="true"

onx_json_out \
    ok true \
    socket "$SOCKET" \
    mode "$SOCKET_MODE" \
    group "$SOCKET_GROUP" \
    exim_access "$EXIM_CAN_READ" \
    config_file "$DROPIN" \
    message "Exim SASL auth socket erisimi acildi (Dovecot reload edildi)"
