#!/usr/bin/env bash
# =============================================================================
# onx-mailbox-remove — Tear down a virtual mailbox
#
# Purpose:
#   Removes the dovecot_users row. Optionally archives the Maildir tree as
#   a gzipped tarball under /var/vmail/_deleted/ before deleting it.
#
# Input (stdin JSON):
#   {
#     "email":       "user@example.com",   -- required
#     "delete_data": true                  -- optional; default false
#                                          --   true  -> archive then rm -rf
#                                          --   false -> DB-only delete; Maildir kept
#   }
#
# Output (stdout JSON):
#   {
#     "email":         "...",
#     "removed":       true,
#     "data_deleted":  true|false,
#     "archived_path": "/var/vmail/_deleted/..." | ""
#   }
#
# Exit codes: 0=ok 1=invalid 2=preflight 3=exec 4=rolled-back 5=rollback-fail
#
# Deployed to: /usr/local/onoxsoft/bin/onx-mailbox-remove
# =============================================================================

set -euo pipefail

SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"
# shellcheck source=_lib/common.sh
source "${SCRIPT_DIR}/_lib/common.sh"

readonly VMAIL_ROOT="/var/vmail"
readonly ARCHIVE_DIR="${VMAIL_ROOT}/_deleted"

require_root
if [[ "${MOCK_MODE}" != "1" ]]; then
    command -v mysql >/dev/null 2>&1 || onx_die 2 "mysql client not found"
    command -v tar   >/dev/null 2>&1 || onx_die 2 "tar not found"
fi

onx_json_input

EMAIL_RAW=$(onx_json_field "email")
DELETE_DATA=$(onx_json_get_bool "${INPUT}" "delete_data" "false")

onx_validate_email "${EMAIL_RAW}" >/dev/null
EMAIL="${ONX_EMAIL}"
LOCAL="${ONX_EMAIL_LOCAL}"
DOMAIN="${ONX_EMAIL_DOMAIN}"

MAILBOX_HOME="${VMAIL_ROOT}/${DOMAIN}/${LOCAL}"
MAILDIR="${MAILBOX_HOME}/Maildir"
onx_validate_vmail_path "${MAILBOX_HOME}" >/dev/null

# ── DB delete ────────────────────────────────────────────────────────────────
# We delete first so the mailbox stops accepting deliveries before we touch
# the on-disk state. If the row never existed we still consider the call
# idempotent and continue to the archive step (operator may be cleaning up
# a half-broken account).
mysql_exec "${DOVECOT_DB_NAME}" \
    "DELETE FROM dovecot_users WHERE email='${EMAIL}';" \
    || onx_die 3 "dovecot_users DELETE failed for ${EMAIL}"

onx_log "dovecot_users row removed: ${EMAIL}"

# Kick any open IMAP/POP3 session so the user can't keep reading mail.
if [[ "${MOCK_MODE}" != "1" ]] && command -v doveadm >/dev/null 2>&1; then
    doveadm kick "${EMAIL}" 2>/dev/null || true
fi

# ── Data handling ────────────────────────────────────────────────────────────
ARCHIVED_PATH=""
DATA_DELETED="false"

if [[ "${DELETE_DATA}" == "true" ]]; then
    if [[ -d "${MAILBOX_HOME}" ]]; then
        mkdir -p "${ARCHIVE_DIR}"
        chmod 700 "${ARCHIVE_DIR}"
        TS="$(date -u +%Y%m%dT%H%M%SZ)"
        # Sanitise email for filename: '@' → '_at_', '.' kept
        SAFE_EMAIL="${EMAIL//@/_at_}"
        ARCHIVED_PATH="${ARCHIVE_DIR}/${SAFE_EMAIL}-${TS}.tar.gz"

        # tar from parent so the archive contains a clean relative path
        if ! tar -czf "${ARCHIVED_PATH}" \
                -C "$(dirname "${MAILBOX_HOME}")" \
                "$(basename "${MAILBOX_HOME}")" 2>/dev/null; then
            onx_die 3 "tar archive failed: ${ARCHIVED_PATH}"
        fi
        chmod 600 "${ARCHIVED_PATH}"
        onx_log "archived to ${ARCHIVED_PATH}"

        # Now nuke the live tree
        rm -rf "${MAILBOX_HOME}"
        DATA_DELETED="true"
        onx_log "live mailbox removed: ${MAILBOX_HOME}"
    else
        onx_log "delete_data=true but no Maildir on disk for ${EMAIL} (continuing)"
    fi
else
    onx_log "delete_data=false → Maildir preserved at ${MAILBOX_HOME}"
fi

onx_audit "onx-mailbox" "remove email=${EMAIL} delete_data=${DELETE_DATA} archive=${ARCHIVED_PATH:-none}"

onx_json_out \
    "email"         "${EMAIL}" \
    "removed"       "true" \
    "data_deleted"  "${DATA_DELETED}" \
    "archived_path" "${ARCHIVED_PATH}"
