#!/bin/bash
# 365-email.sh -- Email Manager
TOOL_NAME="365-email"; TOOL_VERSION="2.0.0"; TOOL_TIER=2; TOOL_BIRD="swan"
TOOL_LOG="/opt/binary/logs/tools/${TOOL_NAME}.log"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
if [[ -f "${SCRIPT_DIR}/common.sh" ]]; then source "${SCRIPT_DIR}/common.sh"
elif [[ -f "${SCRIPT_DIR}/../common.sh" ]]; then source "${SCRIPT_DIR}/../common.sh"
else echo "FATAL: common.sh not found" >&2; exit 1; fi
export BIRD_ID="${TOOL_BIRD}"

_do_send_impl() {
    echo "=== Email Status: ${NODE_ID} ==="
    local svcs=(postfix dovecot)
    for svc in "${svcs[@]}"; do
        if systemctl cat "${svc}.service" &>/dev/null; then
            echo "  ${svc}: $(systemctl is-active $svc 2>/dev/null)"
        else echo "  ${svc}: not_installed"; fi
    done
    if command -v postqueue &>/dev/null; then
        local queue; queue=$(postqueue -p 2>/dev/null | tail -1 | grep -oP '\d+(?= Request)')
        echo "  Mail queue: ${queue:-0} messages"
    fi
    tool_audit "send" "node=${NODE_ID}"
}
_do_status_impl() {
    local postfix="not_installed" dovecot="not_installed"
    systemctl cat postfix.service &>/dev/null && postfix=$(systemctl is-active postfix 2>/dev/null)
    systemctl cat dovecot.service &>/dev/null && dovecot=$(systemctl is-active dovecot 2>/dev/null)
    local s="healthy"; [ "$postfix" != "active" ] && [ "$postfix" != "not_installed" ] && s="degraded"
    echo "{\"tool\":\"${TOOL_NAME}\",\"node\":\"${NODE_ID}\",\"status\":\"${s}\",\"postfix\":\"${postfix}\",\"dovecot\":\"${dovecot}\",\"checked_at\":\"$(date -u +%Y-%m-%dT%H:%M:%SZ)\"}"
}
_do_digest_impl() { _do_send_impl; }
_do_flush_impl() { command -v postsuper &>/dev/null && postsuper -d ALL 2>/dev/null && echo "  [CHANGED] Mail queue flushed"; [ -f "$TOOL_LOG" ] && truncate -s 0 "$TOOL_LOG"; }
tool_help() { echo "${TOOL_NAME} v${TOOL_VERSION} -- Email Manager"; }
do_send()   { tool_wrap "send"   _do_send_impl "$@"; }
do_status() { tool_wrap "status" _do_status_impl "$@"; }
do_digest() { tool_wrap "digest" _do_digest_impl "$@"; }
do_flush()  { tool_wrap "flush"  _do_flush_impl "$@"; }
tool_init; trap 'tool_complete' EXIT
case "${1:---help}" in --send) shift; do_send "$@" ;; --status) shift; do_status "$@" ;; --digest) shift; do_digest "$@" ;; --flush) shift; do_flush "$@" ;; --help) tool_help ;; *) handle_standard_command "$@" ;; esac
