#!/usr/bin/env bash
# Privileged mailbox import runner for Limristem eMail.
# Invoked as root via sudo from the API worker so Maildir files are owned by vmail.
set -Eeuo pipefail

SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
# bin/ layout after install, or scripts/ in the source tree.
if [[ -x "$SCRIPT_DIR/../limristem-mail" ]]; then
  BASE_DIR=$(cd "$SCRIPT_DIR/.." && pwd)
elif [[ -x "$SCRIPT_DIR/../../limristem-mail" ]]; then
  BASE_DIR=$(cd "$SCRIPT_DIR/../.." && pwd)
else
  BASE_DIR=$(cd "$SCRIPT_DIR/.." && pwd)
fi

CLI="$BASE_DIR/limristem-mail"
if [[ ! -x "$CLI" ]]; then
  CLI=$(command -v limristem-mail 2>/dev/null || true)
fi
[[ -n "${CLI:-}" && -x "$CLI" ]] || {
  echo "limristem-mail launcher not found" >&2
  exit 127
}

# Prefer the venv Python used by the launcher.
export LIMRISTEM_MAIL_DISABLE_IMPORT_WORKER=${LIMRISTEM_MAIL_DISABLE_IMPORT_WORKER:-yes}

usage() {
  cat <<'EOF'
Usage: manage-mailbox-import.sh <command> [args]

Commands:
  run <job_id>       Execute a single import job (as root → vmail ownership)
  process-pending    Drain all pending jobs once
  list [--json]      List import jobs
EOF
}

cmd=${1:-}
shift || true

case "$cmd" in
  run)
    job_id=${1:-}
    [[ -n "$job_id" && "$job_id" =~ ^[0-9]+$ ]] || {
      echo "Usage: manage-mailbox-import.sh run <job_id>" >&2
      exit 2
    }
    exec "$CLI" import run-job "$job_id" --json
    ;;
  process-pending|process|drain)
    exec "$CLI" import run-worker --json
    ;;
  list)
    exec "$CLI" import list "$@"
    ;;
  -h|--help|help|"")
    usage
    exit 0
    ;;
  *)
    echo "Unknown command: $cmd" >&2
    usage >&2
    exit 2
    ;;
esac
