#!/bin/bash
# Copyright (c) 2026 HostFog Ltd. All rights reserved.
# Proprietary and confidential. Use is subject to the HostFog licence (LICENSE).
# Unauthorised copying, modification or distribution is prohibited.
# HostFog: sendmail for hosted websites (PHP mail()). Counts the recipients against the account's hourly sending
# limit (hf-mailpolicy), then hands the message to Postfix. If the limit service is not running, mail goes out.
tmp="$(mktemp "${TMPDIR:-/tmp}/hfmail.XXXXXX")" || exec /usr/sbin/sendmail "$@"
trap 'rm -f "$tmp"' EXIT
head -c 52428800 > "$tmp"
n=0; t=0
for a in "$@"; do [[ "$a" == -t ]] && t=1; [[ "$a" != -* && "$a" == *@* ]] && n=$((n + 1)); done
if [[ $t -eq 1 ]]; then
  hdr="$(sed -n '1,/^\r\?$/p' "$tmp" | tr -d '\r' | sed -n '/^\(To\|Cc\|Bcc\):/I{:a;N;/\n[ \t]/ba;p}' | tr '\n' ' ')"
  n=$((n + $(grep -o '@' <<<"$hdr" | wc -l)))
fi
[[ $n -ge 1 ]] || n=1
if [[ -S /run/hostfog-mail.sock ]] && command -v python3 >/dev/null; then
  r="$(python3 -I -c 'import socket,sys
s=socket.socket(socket.AF_UNIX); s.settimeout(5)
try:
    s.connect("/run/hostfog-mail.sock"); s.sendall(("COUNT %s\n" % sys.argv[1]).encode()); print(s.recv(100).decode().strip())
except Exception: print("OK")' "$n" 2>/dev/null)"
  if [[ "$r" == LIMIT ]]; then echo "hf-sendmail: hourly sending limit reached for this hosting account" >&2; exit 75; fi
fi
/usr/sbin/sendmail "$@" < "$tmp"
