#!/bin/bash
# ─────────────────────────────────────────────────────────────────────────────
# One-time MongoDB 3 → FerretDB v1 (SQLite) migration for the WeKan snap.
#
# Runs on startup (called by mongodb-control) BEFORE mongod starts. ONLY the old
# WeKan 6.09 / MongoDB 3.2 (amd64) data needs migrating — a MongoDB 7 database
# works with newest WeKan as-is and is left untouched.
#
# Flow:
#   1. If mongod 7 can open the existing $SNAP_COMMON data, it is MongoDB 6/7:
#      no migration — keep MongoDB (just mark the check done and exit).
#   2. Otherwise it is MongoDB 3.x: start migratemongo's mongod 3.2 to serve it,
#      start a temporary FerretDB v1 (SQLite at <files>/db), and run the importer
#      (migrate-mongo3-to-ferretdb.mjs). It reads the source with the legacy mongo
#      CLI (mongoexport — the modern Node driver can't talk to 3.2) and inserts
#      into FerretDB with the Node driver: text data streamed directly, and
#      CollectionFS/Meteor-Files GridFS attachments+avatars extracted straight to
#      <files>/attachments and <files>/avatars. NO mongodump/mongorestore and no
#      intermediate MongoDB 7. Progress is shown at ROOT_URL.
#   3. On success it switches the snap to database=ferretdb.
#
# Idempotent (completion marker), never deletes the source MongoDB data, only
# switches on success.
#
# IMPORTANT: the amd64 6.09/MongoDB-3.2 path has NOT been exercised end-to-end
# against a real 6.09 snap here — test on a copy first.
# ─────────────────────────────────────────────────────────────────────────────
set -u

if [[ "${PATH:-}" != *"${SNAP_INSTANCE_NAME:-wekan}"* ]]; then
  export PATH="${PATH/\/snap\/wekan\//\/snap\/${SNAP_INSTANCE_NAME:-wekan}\/}"
fi

MARKER="$SNAP_COMMON/.migration-to-ferretdb-done"
DBPATH="$SNAP_COMMON"                                  # old snap's mongod --dbpath
FILES_DIR="$SNAP_COMMON/files"                         # attachments/, avatars/, db/
SQLITE_DIR="$FILES_DIR/db"                             # FerretDB SQLite lives here
SRC_PORT=27099                                         # temp source mongod
TGT_PORT=27098                                         # temp target FerretDB
NODE="$SNAP/bin/node"
IMPORTER="$SNAP/bin/migrate-mongo3-to-ferretdb.mjs"
FERRETDB="$SNAP/ferretdb"
DB_EVAL="$SNAP/bin/db-eval"                            # Node + `mongodb` driver
SRC_URL="mongodb://127.0.0.1:$SRC_PORT/?directConnection=true"
MM="$SNAP/migratemongo"                                # MongoDB 3.2 tools (amd64)
MM_LIB="$MM/lib/x86_64-linux-gnu"                      # old libs for those tools
LOGF="$SNAP_COMMON/migration-mongod.log"

log() { echo "[migration] $*"; }

[ -f "$MARKER" ] && { log "already handled (marker present)."; exit 0; }
if [ ! -f "$DBPATH/WiredTiger" ] && ! ls "$DBPATH"/collection-*.wt >/dev/null 2>&1; then
  log "no existing MongoDB data in $DBPATH; nothing to migrate."
  touch "$MARKER" 2>/dev/null || true
  exit 0
fi

export LC_ALL=C
# Base library path so the snap's own mongod 7 finds its libraries
# (docs/Backup/Backup.md: $SNAP/lib/<arch>-linux-gnu).
export LD_LIBRARY_PATH="$SNAP/lib:$SNAP/lib/x86_64-linux-gnu:$SNAP/lib/aarch64-linux-gnu:${LD_LIBRARY_PATH:-}"

start_mongod() {   # $1 = mongod binary, $2 = LD_LIBRARY_PATH prefix (may be empty)
  LD_LIBRARY_PATH="${2:+$2:}$LD_LIBRARY_PATH" "$1" \
    --dbpath "$DBPATH" --bind_ip 127.0.0.1 --port "$SRC_PORT" \
    --logpath "$LOGF" --logappend --fork >/dev/null 2>&1
}
# Readiness/shutdown for the modern mongod 7 use db-eval (Node + `mongodb` driver).
ready_via_node() {
  local i=0
  while [ $i -lt 20 ]; do
    "$DB_EVAL" ping "$SRC_URL" >/dev/null 2>&1 && return 0
    i=$((i+1)); sleep 1
  done
  return 1
}
stop_via_node() {
  "$DB_EVAL" shutdown "$SRC_URL" >/dev/null 2>&1 || true
  sleep 2
}
# The legacy MongoDB 3.2 client (migratemongo `mongo`) still uses --eval: the
# modern driver cannot speak to a 3.2 server, and mongosh is no longer bundled.
ready_via() {      # $1 = shell binary (legacy mongo), $2 = LD_LIBRARY_PATH prefix
  local i=0
  while [ $i -lt 20 ]; do
    LD_LIBRARY_PATH="${2:+$2:}$LD_LIBRARY_PATH" "$1" --port "$SRC_PORT" --quiet \
        --eval 'db.adminCommand({ping:1}).ok' 2>/dev/null | grep -q 1 && return 0
    i=$((i+1)); sleep 1
  done
  return 1
}
stop_via() {       # $1 = shell binary (legacy mongo), $2 = LD_LIBRARY_PATH prefix
  LD_LIBRARY_PATH="${2:+$2:}$LD_LIBRARY_PATH" "$1" --port "$SRC_PORT" --quiet \
      --eval 'db.getSiblingDB("admin").shutdownServer()' >/dev/null 2>&1 || true
  sleep 2
}

# ── MongoDB 6/7 data? Then NO migration is needed — keep using MongoDB. ───────
log "Checking whether mongod 7 can open the existing data ..."
if start_mongod "$SNAP/bin/mongod" "" && ready_via_node; then
  log "Data is MongoDB 6/7 — no migration needed; keeping MongoDB."
  stop_via_node
  touch "$MARKER"
  exit 0
fi
stop_via_node

# ── Otherwise it is MongoDB 3.x: migrate to FerretDB via the migratemongo CLI. ─
if [ ! -x "$MM/bin/mongod" ] || [ ! -x "$FERRETDB" ] || [ ! -x "$NODE" ] || [ ! -f "$IMPORTER" ]; then
  log "ERROR: MongoDB 3.x data but migration tools missing"
  log "  (migratemongo/ferretdb/node/importer). Leaving the MongoDB data in place."
  exit 0
fi

log "Data is MongoDB 3.x; starting migratemongo mongod 3.2 to read it ..."
if ! start_mongod "$MM/bin/mongod" "$MM_LIB" || ! ready_via "$MM/bin/mongo" "$MM_LIB"; then
  log "ERROR: could not start migratemongo mongod on the MongoDB 3.x data. See $LOGF ."
  stop_via "$MM/bin/mongo" "$MM_LIB"
  exit 0
fi

# Temporary FerretDB v1 (SQLite at <files>/db) as the migration target.
mkdir -p "$SQLITE_DIR"
export DO_NOT_TRACK=1 FERRETDB_TELEMETRY=disable
"$FERRETDB" --handler=sqlite --sqlite-url="file:$SQLITE_DIR/" \
            --listen-addr="127.0.0.1:$TGT_PORT" --telemetry=disable \
            >"$SNAP_COMMON/migration-ferretdb.log" 2>&1 &
FPID=$!
trap 'kill "$FPID" 2>/dev/null || true; stop_via "$MM/bin/mongo" "$MM_LIB"' EXIT INT TERM

WEKAN_PORT="${PORT:-8080}"
log "Migrating MongoDB 3 → FerretDB (CLI read + driver insert). Progress at ${ROOT_URL:-http://localhost:$WEKAN_PORT}"
# NODE_PATH lets the standalone importer resolve its `mongodb`/`bson` imports from
# the WeKan bundle. MONGO_BIN_DIR/MONGO_LIB point at the migratemongo 3.2 tools.
NODE_PATH="$SNAP/programs/server/node_modules" \
MONGO_BIN_DIR="$MM/bin" \
MONGO_LIB="$MM_LIB" \
SRC_PORT="$SRC_PORT" \
SRC_DB="wekan" \
TARGET_MONGO_URL="mongodb://127.0.0.1:$TGT_PORT/wekan" \
FILES_DIR="$FILES_DIR" \
MIGRATION_PORT="$WEKAN_PORT" \
  "$NODE" "$IMPORTER"
rc=$?

if [ "$rc" -eq 0 ]; then
  log "Migration succeeded. Switching database=ferretdb."
  touch "$MARKER"
  snapctl set database=ferretdb 2>/dev/null || true
else
  log "ERROR: migration failed (exit $rc). Will retry on next start; MongoDB 3 data kept."
fi

# temp FerretDB + source mongod are stopped by the EXIT trap.
exit 0
