#!/bin/bash
# zammad-mail-intake - Deliver incoming mail from an MTA pipe transport to Zammad
#
# This script is intended to be called by Postfix (or another MTA) via a pipe
# transport.  Postfix drops privileges to the zammad user before exec'ing this
# script, so no sudo is required here.
#
# Postfix configuration
# ---------------------
# 1. Add the transport service to /etc/postfix/master.cf:
#
#      zammad unix - n n - - pipe
#        flags=Rq user=zammad argv=/usr/sbin/zammad-mail-intake
#
# 2. Enable transport maps in /etc/postfix/main.cf (adapt as needed):
#
#      transport_maps = hash:/etc/postfix/transport
#
# 3. Map the destination domain(s) in /etc/postfix/transport:
#
#      helpdesk.example.com  zammad:
#
# 4. Apply the changes:
#
#      postmap /etc/postfix/transport
#      systemctl reload postfix

APP_DIR="/srv/www/webapps/zammad"

# Source the Zammad environment (RAILS_ENV, REDIS_URL, …)
[ -r /etc/default/zammad ] && . /etc/default/zammad

export RAILS_ENV="${RAILS_ENV:=production}"
export LC_ALL="${LC_ALL:=en_US.UTF-8}"
export LANG="${LANG:=en_US.UTF-8}"

# Rails must be run from the application root
cd "${APP_DIR}" || exit 75   # EX_TEMPFAIL — let the MTA retry

exec "${APP_DIR}/bin/rails" runner 'Channel::Driver::MailStdin.new.process(STDIN.read)'
