#!/usr/bin/env bash
# Fixed privileged Maildir operations; the worker uses directory descriptors so
# changes to the writable mail tree cannot redirect root through a symlink.
set -Eeuo pipefail

SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
BASE_DIR=$(cd "$SCRIPT_DIR/.." && pwd)
# shellcheck source=/dev/null
source "$SCRIPT_DIR/libenv.sh"

for envf in "$BASE_DIR/config/limristem-mail.env" /etc/limristem-mail.env; do
  if [[ -f "$envf" ]]; then
    limristem_mail_load_env_file "$envf"
    break
  fi
done

MAIL_HOME=${LIMRISTEM_MAIL_MAIL_HOME:-/var/mail/vhosts}
VMAIL_UID=${LIMRISTEM_MAIL_VMAIL_UID:-150}
VMAIL_GID=${LIMRISTEM_MAIL_VMAIL_GID:-150}
if id vmail >/dev/null 2>&1; then
  VMAIL_UID=$(id -u vmail)
  VMAIL_GID=$(id -g vmail)
fi

case "${1:-}" in
  -h|--help|help|"")
    printf '%s\n' \
      'Usage: manage-mailbox-fs.sh <command> [domain] [local_part]' \
      'Commands: ensure-mail-home, ensure-maildir, delete-maildir, delete-domain,' \
      '          write-sieve (script on stdin), clear-sieve'
    exit 0
    ;;
esac

# -I ignores Python environment and the caller cwd; the stdlib-only worker is
# deployed alongside this root-owned wrapper and accepts no executable paths.
exec /usr/bin/python3 -I "$SCRIPT_DIR/mailbox-fs.py" \
  "$MAIL_HOME" "$VMAIL_UID" "$VMAIL_GID" "$BASE_DIR" "$@"
