#!/usr/bin/env bash
# Wrapper: load DB env and run Python auth verifier under the package venv.
# Invoked by /etc/dovecot/limristem-auth-passdb.lua (Dovecot 2.4 Lua passdb).
set -euo pipefail

SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
BASE_DIR=$(cd "$SCRIPT_DIR/.." && pwd)
if [[ -f "$BASE_DIR/bin/libenv.sh" ]]; then
  # shellcheck source=/dev/null
  source "$BASE_DIR/bin/libenv.sh"
elif [[ -f "$BASE_DIR/scripts/libenv.sh" ]]; then
  # shellcheck source=/dev/null
  source "$BASE_DIR/scripts/libenv.sh"
fi

ENV_FILE="${LIMRISTEM_MAIL_ENV_FILE:-}"
if [[ -z "$ENV_FILE" ]]; then
  for candidate in "$BASE_DIR/config/limristem-mail.env" /etc/limristem-mail.env; do
    if [[ -f "$candidate" ]]; then
      ENV_FILE=$candidate
      break
    fi
  done
fi
if [[ -n "${ENV_FILE:-}" && -f "$ENV_FILE" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$ENV_FILE"
  set +a
fi

PYTHON="$BASE_DIR/.venv/bin/python3"
if [[ ! -x "$PYTHON" ]]; then
  PYTHON=$(command -v python3 || true)
fi
if [[ -z "${PYTHON:-}" ]]; then
  exit 111
fi

HELPER="$SCRIPT_DIR/dovecot-auth-verify"
if [[ ! -f "$HELPER" ]]; then
  HELPER="$BASE_DIR/bin/dovecot-auth-verify"
fi
if [[ ! -f "$HELPER" ]]; then
  exit 111
fi

exec "$PYTHON" "$HELPER" "$@"
