#!/usr/bin/env bash
# Instala ferramentas de migração de e-mail (Spec 013)
set -euo pipefail

TOOLS_DIR="${MIGRATION_TOOLS_PATH:-/opt/migration-tools}"
IMAP_UPLOAD_REPO="https://github.com/rgladwell/imap-upload.git"

echo "==> Instalando pacotes base (imapsync, pst-utils)..."
export DEBIAN_FRONTEND=noninteractive
apt-get update -qq
apt-get install -y -qq imapsync pst-utils python3 python3-pip git curl

echo "==> Instalando imap-upload em ${TOOLS_DIR}/imap-upload..."
mkdir -p "${TOOLS_DIR}"
if [[ ! -d "${TOOLS_DIR}/imap-upload/.git" ]]; then
  git clone --depth 1 "${IMAP_UPLOAD_REPO}" "${TOOLS_DIR}/imap-upload"
else
  git -C "${TOOLS_DIR}/imap-upload" pull --ff-only || true
fi
chmod +x "${TOOLS_DIR}/imap-upload/imap_upload.py" 2>/dev/null || true

echo "==> Verificação..."
command -v imapsync >/dev/null && imapsync --version | head -1 || echo "WARN: imapsync não encontrado"
command -v readpst >/dev/null && readpst -V 2>&1 | head -1 || echo "WARN: readpst não encontrado"
test -f "${TOOLS_DIR}/imap-upload/imap_upload.py" && echo "OK: imap_upload.py"

echo "==> Concluído. Ver specs/013-email-server-migration/quickstart.md"
