#!/usr/bin/env bash
set -euo pipefail

APP_DIR="$(readlink -f "$(dirname "${BASH_SOURCE[0]}")/..")"
APP_COMPOSE_FILE="${APP_DIR}/docker-compose.yml"
APP_COMPOSE_BACKUP_FILE="${APP_DIR}/docker-compose.yml.v016-migration.bak"

LEGACY_ROOT="${APP_DATA_ROOT:-${APP_DIR}/data}"
LEGACY_CONFIG_TOML="${LEGACY_ROOT}/etc/config.toml"
LEGACY_DATA_DIR="${LEGACY_ROOT}/data"
FINAL_ETC_DIR="${LEGACY_ROOT}/etc"
FINAL_SERVER_DIR="${LEGACY_ROOT}/server"
FINAL_LOGS_DIR="${LEGACY_ROOT}/logs"
FINAL_CONFIG_JSON="${FINAL_ETC_DIR}/config.json"

MIGRATION_DIR="${LEGACY_ROOT}/migration-v016"
MIGRATION_SCRIPT="${MIGRATION_DIR}/migrate_v016.py"
MIGRATION_SCRIPT_URL="https://raw.githubusercontent.com/stalwartlabs/stalwart/18f4e9505027d790fd7e9fdad7f922be6719101d/resources/scripts/migrate_v016.py"
MIGRATION_PYTHON_IMAGE="python:3.13.16-alpine3.24@sha256:2d9aefe2fef018a7eb2c13064c89c71929800fd2e5dccdbf52ea5da5bb8d929a"
STALWART_CLI_INSTALLER_URL="https://github.com/stalwartlabs/cli/releases/download/v1.0.4/stalwart-cli-installer.sh"
GENERATED_CONFIG_JSON="${MIGRATION_DIR}/config.json"
DUMP_LOG="${MIGRATION_DIR}/dump.log"
CONVERT_LOG="${MIGRATION_DIR}/convert.log"
SERVER_ENV_JSON="${MIGRATION_DIR}/server-env.json"
FALLBACK_DEFAULT_HOSTNAME="stalwart.example.com"

LOCK_FILE="${LEGACY_ROOT}/.v016_migrating"
DONE_FILE="${LEGACY_ROOT}/.v016_migrated"
DUMP_DONE_FILE="${LEGACY_ROOT}/.v016_dumped"
APPLY_DONE_FILE="${LEGACY_ROOT}/.v016_applied"
RECOVERY_STARTED_FILE="${LEGACY_ROOT}/.v016_recovery_started"

OLD_IMAGE="stalwartlabs/stalwart:v0.15.5@sha256:dcf575db2d53d9ef86d6ced8abe4ba491984659a0f8862cc6079ee7b41c3c568"
FINAL_IMAGE="stalwartlabs/stalwart:v0.16.27@sha256:c429b311c93db5606598abc1c68225a85a6953183848ae01bee9c6a98885836c"
OLD_PROXY_PORT="8745"
OLD_HTTP_PORT="18080"
OLD_HTTP_URL=""
RECOVERY_CONTAINER="stalwart-v016-recovery"
RECOVERY_PORT="38080"
OLD_APP_STARTED=0

restore_compose() {
  if [[ -f "${APP_COMPOSE_BACKUP_FILE}" ]]; then
    cp "${APP_COMPOSE_BACKUP_FILE}" "${APP_COMPOSE_FILE}"
  fi
}

block_production_start() {
  # Umbrel continues starting containers even when pre-start fails. Keep the
  # production service from opening an empty or partially migrated database.
  if [[ ! -f "${APP_COMPOSE_BACKUP_FILE}" ]]; then
    cp "${APP_COMPOSE_FILE}" "${APP_COMPOSE_BACKUP_FILE}"
  fi
  yq '.x-stalwart-migration-guard = true | .services.server.entrypoint = ["/bin/sh", "-c", "echo Stalwart migration incomplete. Check the app logs before retrying. >&2; exit 1"] | .services.server.restart = "no"' "${APP_COMPOSE_BACKUP_FILE}" > "${APP_COMPOSE_FILE}.v016-guard.tmp"
  mv "${APP_COMPOSE_FILE}.v016-guard.tmp" "${APP_COMPOSE_FILE}"
}

cleanup() {
  local exit_code=$?

  if [[ ${exit_code} -ne 0 ]]; then
    echo "Stalwart v0.16 migration failed. Preserving migration files and stopping the server."
    if [[ "${OLD_APP_STARTED}" == "1" ]]; then
      "${UMBREL_ROOT}/scripts/app" stop "${APP_ID}" >/dev/null 2>&1 || true
    fi
    docker rm -f "${RECOVERY_CONTAINER}" >/dev/null 2>&1 || true
    block_production_start
  fi

  rm -f "${LOCK_FILE}"
}

# ---------------------------------------------------------------------------
# v0.16 -> v1
# Stalwart v1 refuses to open a v0.16 datastore. Upstream's stalwart-migrate
# copies it into a new v1 store and verifies every account. The v0.16 store is
# opened read-only and kept in server-v0.16.
V1_MIGRATE_IMAGE="stalwartlabs/stalwart-migrate:1.0.7@sha256:368725b2d5e0ff2ea673e51d5c39cddc7cc8bfbc6c88cb46b9d627039862f27b"
V1_READY_FILE="${LEGACY_ROOT}/.v1_ready"
V1_VERIFIED_FILE="${LEGACY_ROOT}/.v1_verified"
V1_TARGET_DIR="${LEGACY_ROOT}/server-v1"
V1_ORIGINAL_DIR="${LEGACY_ROOT}/server-v0.16"
V1_STATE_DIR="${LEGACY_ROOT}/migration-v1"

v1_migrate() {
  docker run --rm --network none --user 1000:1000 \
    -v "${FINAL_ETC_DIR}:/etc/stalwart" \
    -v "${FINAL_ETC_DIR}:/etc/stalwart-v1" \
    -v "${FINAL_SERVER_DIR}:/var/lib/stalwart" \
    -v "${V1_TARGET_DIR}:/var/lib/stalwart-v1" \
    -v "${V1_STATE_DIR}:/var/lib/stalwart-migrate" \
    "${V1_MIGRATE_IMAGE}" "$@" --state /var/lib/stalwart-migrate
}

run_v1_migration() {
  if [[ -f "${V1_VERIFIED_FILE}" ]]; then
    # Finish a folder swap that was interrupted after verification.
    if [[ -d "${V1_TARGET_DIR}" ]]; then
      [[ -d "${V1_ORIGINAL_DIR}" ]] || mv "${FINAL_SERVER_DIR}" "${V1_ORIGINAL_DIR}"
      mv "${V1_TARGET_DIR}" "${FINAL_SERVER_DIR}"
    fi
    touch "${V1_READY_FILE}"
    return
  fi

  if [[ ! -s "${FINAL_CONFIG_JSON}" ]]; then
    # A fresh install, or a v0.16 install that never finished setup: no mail to
    # migrate. Set aside any v0.16 setup-mode store so v1 can start its own.
    if [[ -n "$(ls -A "${FINAL_SERVER_DIR}" 2>/dev/null)" ]]; then
      mv "${FINAL_SERVER_DIR}" "${V1_ORIGINAL_DIR}"
    fi
    mkdir -p "${FINAL_SERVER_DIR}"
    chown 1000:1000 "${FINAL_SERVER_DIR}"
    touch "${V1_READY_FILE}"
    return
  fi

  echo "Migrating Stalwart mail and settings to v1. Large mailboxes take longer..."
  local needed_kb available_kb questions
  needed_kb="$(du -sk "${FINAL_SERVER_DIR}" | cut -f1)"
  available_kb="$(df -Pk "${LEGACY_ROOT}" | awk 'NR==2 {print $4}')"
  if (( available_kb < needed_kb + 524288 )); then
    echo "Error: not enough free space. The migration needs a second copy of the mail store ($(( needed_kb / 1024 + 512 )) MiB)."
    return 1
  fi

  docker image inspect "${V1_MIGRATE_IMAGE}" >/dev/null 2>&1 || docker pull "${V1_MIGRATE_IMAGE}" >/dev/null
  rm -rf "${V1_TARGET_DIR}" "${V1_STATE_DIR}"
  mkdir -p "${V1_TARGET_DIR}" "${V1_STATE_DIR}"
  chmod 700 "${V1_STATE_DIR}"
  chown 1000:1000 "${V1_TARGET_DIR}" "${V1_STATE_DIR}"

  # Answers to the questions upstream's `prepare` asks interactively: migrate
  # everything and keep the behaviour the v0.16 install had.
  cat > "${V1_STATE_DIR}/answers.toml" <<'ANSWERS'
version = 1
[global.categories]
include = ["settings", "principals", "mail", "calendars", "contacts", "files", "sieve", "identities", "push_subscriptions", "spam_samples", "reports", "archive", "spam_model", "queue", "tasks", "telemetry"]
[global.changed_defaults]
policy = "pin"
[global.new_permissions]
action = "none"
[global.oauth_client_scopes]
scopes = "interoperable"
[global.encryption_at_rest]
header_protection = "none"
ANSWERS
  chown 1000:1000 "${V1_STATE_DIR}/answers.toml"

  # The first pass lists any per-install questions. Only the OAuth client
  # re-registration notice is accepted here; anything else (OIDC directories,
  # proxies, AI models) needs a person and fails the second pass.
  v1_migrate prepare --source /etc/stalwart/config.json --non-interactive > "${V1_STATE_DIR}/prepare.log" 2>&1 || true
  questions="$(sed -n 's/^# \[\(instance\.oauth_registration\..*\)\]$/[\1]\naction = "accept"/p' "${V1_STATE_DIR}/answers.toml")"
  [[ -z "${questions}" ]] || printf '%s\n' "${questions}" >> "${V1_STATE_DIR}/answers.toml"
  v1_migrate prepare --source /etc/stalwart/config.json --non-interactive >> "${V1_STATE_DIR}/prepare.log" 2>&1

  v1_migrate run --source /etc/stalwart/config.json --target /etc/stalwart-v1/config.json \
    --target-path-map /var/lib/stalwart=/var/lib/stalwart-v1 --final --yes --verify-full \
    > "${V1_STATE_DIR}/run.log" 2>&1

  touch "${V1_VERIFIED_FILE}"
  mv "${FINAL_SERVER_DIR}" "${V1_ORIGINAL_DIR}"
  mv "${V1_TARGET_DIR}" "${FINAL_SERVER_DIR}"
  touch "${V1_READY_FILE}"
  echo "Stalwart v1 migration verified and completed. The v0.16 data is kept in ${V1_ORIGINAL_DIR}."
}

# Runs once the data is in the v0.16 layout (or there is no data yet).
migrate_to_v1() {
  trap - EXIT
  rm -f "${LOCK_FILE}"
  [[ ! -f "${V1_READY_FILE}" ]] || exit 0

  local status=0
  set +e
  ( set -euo pipefail; run_v1_migration )
  status=$?
  set -e
  if [[ ${status} -ne 0 ]]; then
    echo "Stalwart v1 migration failed. Your v0.16 data is untouched and the server stays stopped."
    echo "See ${V1_STATE_DIR}/prepare.log and run.log, then restart the app to retry."
    tail -n 20 "${V1_STATE_DIR}/prepare.log" "${V1_STATE_DIR}/run.log" 2>/dev/null || true
    block_production_start
    exit 1
  fi
  exit 0
}
# ---------------------------------------------------------------------------

# The nested v0.15 start must not install the outer migration's cleanup trap:
# otherwise its successful exit removes the lock while migration is running.
if [[ -f "${LOCK_FILE}" ]]; then
  migration_pid="$(cat "${LOCK_FILE}")"
  if [[ "${migration_pid}" =~ ^[0-9]+$ ]] && kill -0 "${migration_pid}" 2>/dev/null; then
    echo "Stalwart v0.16 migration already in progress. Allowing nested app start to continue."
    exit 0
  fi
  rm -f "${LOCK_FILE}"
fi

# Both bootstrap and migrated defaults use this file tracer path. Prepare it
# on fresh installs and existing v0.16 installs, including completed migrations.
mkdir -p "${FINAL_LOGS_DIR}"
chown 1000:1000 "${FINAL_LOGS_DIR}"

# An app-store update replaces compose, but retains migration checkpoint files.
# Do not restore an older package over a newly supplied production compose.
if [[ -f "${APP_COMPOSE_BACKUP_FILE}" ]] &&
   [[ "$(yq '.x-stalwart-migration-guard // false' "${APP_COMPOSE_FILE}")" != "true" ]] &&
   [[ "$(yq '.services.server.image' "${APP_COMPOSE_FILE}")" != "${OLD_IMAGE}" ]]; then
  cp "${APP_COMPOSE_FILE}" "${APP_COMPOSE_BACKUP_FILE}"
fi

if [[ -f "${DONE_FILE}" ]]; then
  restore_compose
  rm -f "${APP_COMPOSE_BACKUP_FILE}"
  migrate_to_v1
fi

if [[ -f "${FINAL_CONFIG_JSON}" && ! -f "${LEGACY_CONFIG_TOML}" && ! -d "${LEGACY_DATA_DIR}" && ! -f "${RECOVERY_STARTED_FILE}" ]]; then
  touch "${DONE_FILE}"
  migrate_to_v1
fi

if [[ ! -f "${LEGACY_CONFIG_TOML}" && ! -d "${LEGACY_DATA_DIR}" && ! -f "${RECOVERY_STARTED_FILE}" ]]; then
  mkdir -p "${FINAL_ETC_DIR}" "${FINAL_SERVER_DIR}"
  touch "${DONE_FILE}"
  migrate_to_v1
fi

trap cleanup EXIT

require_command() {
  local command_name="${1}"

  if ! command -v "${command_name}" >/dev/null 2>&1; then
    echo "Error: ${command_name} is required for the Stalwart v0.16 migration."
    exit 1
  fi
}

wait_for_url() {
  local url="${1}"
  local max_wait="${2}"
  local elapsed=0
  local interval=5

  while [[ ${elapsed} -lt ${max_wait} ]]; do
    if curl -fsSk "${url}" >/dev/null 2>&1; then
      return 0
    fi

    sleep "${interval}"
    elapsed=$((elapsed + interval))
  done

  echo "Timed out waiting for ${url}"
  return 1
}

wait_for_v015_api() {
  local max_wait="${1}"
  local elapsed=0
  local interval=5
  local url
  local urls=(
    "http://127.0.0.1:${OLD_PROXY_PORT}"
    "http://127.0.0.1:${OLD_HTTP_PORT}"
  )

  while [[ ${elapsed} -lt ${max_wait} ]]; do
    for url in "${urls[@]}"; do
      if curl -fsS -u "admin:${APP_PASSWORD}" "${url}/api/settings/list?prefix=&page=1&limit=1" >/dev/null 2>&1; then
        OLD_HTTP_URL="${url}"
        return 0
      fi
    done

    sleep "${interval}"
    elapsed=$((elapsed + interval))
  done

  echo "Timed out waiting for the Stalwart v0.15 management API"
  return 1
}

prepare_v015_fallback_admin() {
  local new_secret

  if [[ ! -f "${LEGACY_CONFIG_TOML}" ]]; then
    return 0
  fi

  if ! grep -q "^\[authentication\.fallback-admin\]" "${LEGACY_CONFIG_TOML}"; then
    return 0
  fi

  new_secret="$(openssl passwd -6 -salt 8woP51TKJO.JKOp9 "${APP_PASSWORD}")"
  sed -i.bak "/^\[authentication\.fallback-admin\]/,/^\[/s|^secret = .*|secret = \"${new_secret}\"|" "${LEGACY_CONFIG_TOML}"
  rm -f "${LEGACY_CONFIG_TOML}.bak"
}

switch_compose_to_v015() {
  restore_compose
  yq -i ".services.server.image = \"${OLD_IMAGE}\"" "${APP_COMPOSE_FILE}"
  yq -i '.services.server.user = "1000:1000"' "${APP_COMPOSE_FILE}"
  yq -i '.services.server.volumes = ["${APP_DATA_DIR}/data:/opt/stalwart"]' "${APP_COMPOSE_FILE}"
  yq -i ".services.server.ports += [\"127.0.0.1:${OLD_HTTP_PORT}:8080\"]" "${APP_COMPOSE_FILE}"
}

download_migration_script() {
  mkdir -p "${MIGRATION_DIR}"
  chmod 0700 "${MIGRATION_DIR}"
  curl -fsSL "${MIGRATION_SCRIPT_URL}" -o "${MIGRATION_SCRIPT}"
  chmod 0755 "${MIGRATION_SCRIPT}"
}

run_migration_script() {
  docker run --rm -i \
    --network host \
    -v "${MIGRATION_DIR}:/migration" \
    -v "${LEGACY_ROOT}:/opt/stalwart:ro" \
    -w /migration \
    "${MIGRATION_PYTHON_IMAGE}" \
    sh -ec 'python -m pip install --quiet --no-cache-dir requests urllib3
      python - "$@"' migrate_v016 "$@" <<'PYTHON'
import json, os, runpy, sys
from pathlib import Path
# Resolve legacy key/certificate macros with the server environment, not the
# migration container environment. Keep this snapshot private on disk.
env_path = Path("/migration/server-env.json")
if env_path.exists():
    for entry in json.loads(env_path.read_text()):
        key, _, value = entry.partition("=")
        os.environ[key] = value
sys.argv = ["/migration/migrate_v016.py", *sys.argv[1:]]
helper = runpy.run_path(sys.argv[0])
if sys.argv[1:2] == ["convert"]:
    dump_log = Path("/migration/dump.log")
    unsupported_tenant = "  WARN skipping principal type 'tenant': Server error on /api/principal: {'error': 'unsupported', 'details': 'Enterprise feature'}"
    if dump_log.exists() and unsupported_tenant in dump_log.read_text().splitlines():
        settings = json.loads(Path("/migration/settings.json").read_text())
        principals = json.loads(Path("/migration/principals.json").read_text())
        # An expired enterprise license produces the same response as Community
        # Edition. Never silently remove ownership from existing tenant data.
        if any(helper["pv_string"](settings.get(key)).strip() for key in
               ("enterprise.license-key", "enterprise.api-key")) or any(
            helper["pv_string"](principal.get("tenant")) for principal in principals
        ):
            raise SystemExit("Error: tenant export is unavailable for a licensed or tenant-owned deployment. Restore enterprise access and redump before migrating.")
sys.exit(helper["main"](sys.argv[1:]))
PYTHON
}

sanitize_export_snapshot() {
  docker run --rm -i \
    -e "FALLBACK_DEFAULT_HOSTNAME=${FALLBACK_DEFAULT_HOSTNAME}" \
    -v "${MIGRATION_DIR}:/migration" \
    -w /migration \
    "${MIGRATION_PYTHON_IMAGE}" \
    python - <<'PY'
import json
import os
import re
from pathlib import Path

path = Path("/migration/export.json")
ops = []
with path.open("r", encoding="utf-8") as handle:
    for line in handle:
        line = line.strip()
        if line:
            ops.append(json.loads(line))

def valid_hostname(value):
    if not isinstance(value, str):
        return False
    value = value.strip().rstrip(".")
    if not value or len(value) > 253 or "." not in value:
        return False
    reserved_tlds = {"test", "local", "localhost", "invalid", "example"}
    label_re = re.compile(r"^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$")
    labels = value.split(".")
    return labels[-1].lower() not in reserved_tlds and all(label_re.match(label) for label in labels)

domains = {}
for op in ops:
    if op.get("@type") == "create" and op.get("object") == "Domain":
        for create_id, value in op.get("value", {}).items():
            name = value.get("name")
            if valid_hostname(name):
                domains[create_id] = name.strip().rstrip(".").lower()

changed = False
for op in ops:
    if op.get("@type") != "update" or op.get("object") != "SystemSettings":
        continue
    value = op.get("value", {})
    current = value.get("defaultHostname")
    if valid_hostname(current):
        value["defaultHostname"] = current.strip().rstrip(".").lower()
        continue
    default_domain_id = str(value.get("defaultDomainId", "")).removeprefix("#")
    replacement = domains.get(default_domain_id)
    if replacement is None and domains:
        replacement = sorted(domains.values())[0]
    if replacement is None:
        replacement = os.environ["FALLBACK_DEFAULT_HOSTNAME"]
    value["defaultHostname"] = replacement
    print(f"replaced invalid SystemSettings.defaultHostname {current!r} with {replacement!r}")
    changed = True

if changed:
    tmp = path.with_suffix(".json.tmp")
    with tmp.open("w", encoding="utf-8") as handle:
        for op in ops:
            handle.write(json.dumps(op, ensure_ascii=False))
            handle.write("\n")
    tmp.replace(path)
PY
}

dump_legacy_settings() {
  docker inspect --format '{{json .Config.Env}}' "${APP_ID}_server_1" > "${SERVER_ENV_JSON}"
  chmod 0600 "${SERVER_ENV_JSON}"
  if ! run_migration_script dump \
    --url "${OLD_HTTP_URL:-http://127.0.0.1:${OLD_HTTP_PORT}}" \
    --username admin \
    --password "${APP_PASSWORD}" \
    --settings /migration/settings.json \
    --principals /migration/principals.json 2> "${DUMP_LOG}"; then
    cat "${DUMP_LOG}" >&2
    return 1
  fi
  cat "${DUMP_LOG}" >&2
  # The upstream helper probes tenant principals on Community Edition too.
  # Only its exact unsupported-enterprise response is an expected omission.
  local community_tenant_warning="  WARN skipping principal type 'tenant': Server error on /api/principal: {'error': 'unsupported', 'details': 'Enterprise feature'}"
  if grep -E 'WARN (skipping|failed)|warning:.*principal' "${DUMP_LOG}" |
    grep -Fvx "${community_tenant_warning}" >/dev/null; then
    echo "Error: the legacy export is incomplete. Review ${DUMP_LOG} before retrying."
    return 1
  fi
}

convert_legacy_settings() {
  # Always convert the original dump with the pinned helper, including retries
  # of exports produced by an older helper. Never redump a migrated datastore.
  if ! run_migration_script convert \
    --settings /migration/settings.json \
    --principals /migration/principals.json \
    --config /migration/config.json \
    --output /migration/export.json \
    --patch-paths /opt/stalwart/etc=/etc/stalwart \
    --patch-paths /opt/stalwart/logs=/var/log/stalwart \
    --patch-paths /opt/stalwart=/var/lib/stalwart \
    --unmigrated-output /migration/unmigrated.txt 2> "${CONVERT_LOG}"; then
    cat "${CONVERT_LOG}" >&2
    return 1
  fi
  cat "${CONVERT_LOG}" >&2
  if grep -Eq 'warning: (dropping|skipping|renaming)' "${CONVERT_LOG}"; then
    echo "Error: migration would omit or rename legacy objects. Review ${CONVERT_LOG} before retrying."
    return 1
  fi
  sanitize_export_snapshot
}

prepare_v016_layout() {
  mkdir -p "${FINAL_ETC_DIR}" "${FINAL_SERVER_DIR}"

  # Preserve the old /opt/stalwart directory structure: a store at
  # /opt/stalwart/data must exist at /var/lib/stalwart/data after conversion.
  # Also retain custom app-local blob directories. etc is already mounted
  # separately (as are logs), and the original files remain as a local backup.
  local path
  shopt -s dotglob nullglob
  for path in "${LEGACY_ROOT}"/*; do
    case "${path}" in
      "${FINAL_ETC_DIR}"|"${FINAL_SERVER_DIR}"|"${FINAL_LOGS_DIR}"|"${MIGRATION_DIR}"|"${LEGACY_ROOT}"/.v016_*) continue ;;
    esac
    [[ -e "${path}" ]] || continue
    cp -a "${path}" "${FINAL_SERVER_DIR}/"
  done
  shopt -u dotglob nullglob

  cp "${GENERATED_CONFIG_JSON}" "${FINAL_CONFIG_JSON}"
  chown -R 1000:1000 "${FINAL_ETC_DIR}" "${FINAL_SERVER_DIR}"
}

start_recovery_container() {
  docker rm -f "${RECOVERY_CONTAINER}" >/dev/null 2>&1 || true

  # Starting v0.16 mutates the datastore before the export is applied. A failed
  # or interrupted attempt requires upstream partial-apply/backup recovery,
  # especially for external databases that cannot be restored from local files.
  touch "${RECOVERY_STARTED_FILE}"
  docker run -d \
    --name "${RECOVERY_CONTAINER}" \
    --user "1000:1000" \
    -e STALWART_RECOVERY_MODE=1 \
    -e "STALWART_RECOVERY_ADMIN=admin:${APP_PASSWORD}" \
    -p "127.0.0.1:${RECOVERY_PORT}:8080" \
    -v "${FINAL_ETC_DIR}:/etc/stalwart" \
    -v "${FINAL_SERVER_DIR}:/var/lib/stalwart" \
    -v "${FINAL_LOGS_DIR}:/var/log/stalwart" \
    "${FINAL_IMAGE}"

  wait_for_url "http://127.0.0.1:${RECOVERY_PORT}/healthz/live" 300
}

apply_export() {
  if [[ -f "${APPLY_DONE_FILE}" ]]; then
    return 0
  fi

  docker run --rm \
    --network host \
    -e STALWART_URL="http://127.0.0.1:${RECOVERY_PORT}" \
    -e STALWART_USER=admin \
    -e "STALWART_PASSWORD=${APP_PASSWORD}" \
    -e "STALWART_CLI_INSTALLER_URL=${STALWART_CLI_INSTALLER_URL}" \
    -e STALWART_CLI_UNMANAGED_INSTALL=/migration/stalwart-cli \
    -e STALWART_CLI_NO_MODIFY_PATH=1 \
    -e STALWART_CLI_PRINT_QUIET=1 \
    -v "${MIGRATION_DIR}:/migration" \
    -w /migration \
    "${MIGRATION_PYTHON_IMAGE}" \
    sh -ec '
      if [ ! -x /migration/stalwart-cli/stalwart-cli ]; then
        rm -rf /migration/stalwart-cli
        mkdir -p /migration/stalwart-cli
        wget -qO- "$STALWART_CLI_INSTALLER_URL" | sh
      fi

      /migration/stalwart-cli/stalwart-cli apply --file /migration/export.json
    '

  touch "${APPLY_DONE_FILE}"
}

stop_recovery_container() {
  local recovery_id
  recovery_id="$(docker ps -aq --filter "name=^/${RECOVERY_CONTAINER}$")"
  if [[ -n "${recovery_id}" ]]; then
    docker stop "${recovery_id}" >/dev/null
    docker rm "${recovery_id}" >/dev/null
  fi
}

require_command curl
require_command docker
require_command openssl
require_command yq

if [[ -z "${APP_PASSWORD:-}" ]]; then
  echo "Error: APP_PASSWORD is required for the Stalwart v0.16 migration."
  exit 1
fi

umask 077
printf '%s\n' "$$" > "${LOCK_FILE}"
block_production_start

if [[ -f "${APPLY_DONE_FILE}" ]]; then
  # A crash after apply must not recopy the v0.15 database over migrated mail.
  stop_recovery_container
  touch "${DONE_FILE}"
  restore_compose
  rm -f "${APP_COMPOSE_BACKUP_FILE}"
  migrate_to_v1
fi

if [[ -f "${RECOVERY_STARTED_FILE}" ]] ||
   [[ -f "${DUMP_DONE_FILE}" && -f "${FINAL_CONFIG_JSON}" && ! -f "${SERVER_ENV_JSON}" ]]; then
  echo "Error: an earlier v0.16 migration was interrupted after opening the datastore."
  echo "The server is stopped to preserve data. Do not delete accounts or rerun v0.15."
  echo "Follow upstream partial-apply recovery or restore the pre-migration backup:"
  echo "https://github.com/stalwartlabs/stalwart/blob/v0.16.26/UPGRADING/v0_16.md#recovering-from-a-partial-apply"
  exit 1
fi

echo "Starting Stalwart v0.15 to v0.16 migration..."
download_migration_script

if [[ ! -f "${DUMP_DONE_FILE}" || ! -f "${SERVER_ENV_JSON}" ]]; then
  rm -f "${DUMP_DONE_FILE}"
  prepare_v015_fallback_admin
  switch_compose_to_v015
  OLD_APP_STARTED=1
  "${UMBREL_ROOT}/scripts/app" start "${APP_ID}"
  wait_for_v015_api 300
  dump_legacy_settings
  "${UMBREL_ROOT}/scripts/app" stop "${APP_ID}"
  OLD_APP_STARTED=0
  # A reusable snapshot must also certify that its source datastore is stopped.
  touch "${DUMP_DONE_FILE}"
fi
block_production_start
convert_legacy_settings
prepare_v016_layout
start_recovery_container
apply_export
stop_recovery_container

touch "${DONE_FILE}"
restore_compose
rm -f "${APP_COMPOSE_BACKUP_FILE}"

echo "Stalwart v0.16 migration completed."
migrate_to_v1
