#!/bin/bash

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

# get wekan/mongo settings
source $SNAP/bin/wekan-read-settings

# Sibling snap service prefix ("wekan", or the instance name for a parallel install).
WEKAN_SNAP_SVC="${SNAP_INSTANCE_NAME:-${SNAP_NAME:-wekan}}"

# ---------------------------------------------------------------------------------------
# Decide which database to ACTUALLY use, based on what data exists on disk - not on the
# `database` snap setting alone. That setting can be flipped to ferretdb before any data
# has been migrated, and the migration's INTERNAL `snapctl set` does not re-run the
# configure hook, so it can also be stale. Before committing to FerretDB we check:
#   - FerretDB (SQLite) data: $SNAP_COMMON/files/db      (non-empty dir = FerretDB has data)
#   - MongoDB (WiredTiger) data: $SNAP_COMMON            (WiredTiger / collection-*.wt files)
#   - migration-success marker: $SNAP_COMMON/.migration-to-ferretdb-done
# ---------------------------------------------------------------------------------------
FERRETDB_SQLITE_DIR="$SNAP_COMMON/files/db"
MIGRATION_DONE_MARKER="$SNAP_COMMON/.migration-to-ferretdb-done"

ferretdb_has_data=false
if [ -d "$FERRETDB_SQLITE_DIR" ] && [ -n "$(ls -A "$FERRETDB_SQLITE_DIR" 2>/dev/null)" ]; then
    ferretdb_has_data=true
fi

mongodb_has_data=false
if [ -f "$SNAP_COMMON/WiredTiger" ] || ls "$SNAP_COMMON"/collection-*.wt >/dev/null 2>&1; then
    mongodb_has_data=true
fi

echo "Database selection: setting='${DATABASE:-mongodb}' ferretdb_has_data=${ferretdb_has_data} mongodb_has_data=${mongodb_has_data}"

# If the migration finished successfully (marker present), FerretDB is authoritative:
# force ferretdb - in case the setting drifted back to mongodb, or the services were left
# stopped/disabled (the migration's internal `snapctl set` does not re-run the configure
# hook that flips them). This makes WeKan self-healing instead of waiting forever for a
# MongoDB that is gone.
if [ -f "$MIGRATION_DONE_MARKER" ] && [ "ferretdb" != "$DATABASE" ]; then
    echo "MongoDB -> FerretDB migration already finished; forcing database=ferretdb."
    export DATABASE="ferretdb"
    snapctl set database=ferretdb 2>/dev/null || true
fi

# SAFETY: never start an EMPTY FerretDB while real data still lives in MongoDB. This is the
# case where database=ferretdb was selected (or forced) but the migration never ran, so
# there is no SQLite database yet - starting FerretDB would make WeKan look completely
# wiped. Revert to MongoDB (which still has the data) and tell the user to migrate first.
if [ "ferretdb" = "$DATABASE" ] && [ "$ferretdb_has_data" != "true" ] && [ "$mongodb_has_data" = "true" ]; then
    echo "========================================================================"
    echo "WeKan: database=ferretdb, but the FerretDB SQLite database is empty/missing:"
    echo "  $FERRETDB_SQLITE_DIR"
    echo "and MongoDB (WiredTiger) data IS present in $SNAP_COMMON."
    echo ""
    echo "Refusing to start an EMPTY FerretDB - that would look like all data was lost."
    echo "Reverting to database=mongodb so your existing data stays available."
    echo ""
    echo "To move this server to FerretDB, run the MongoDB -> FerretDB migration first"
    echo "(it fills $FERRETDB_SQLITE_DIR and only switches to ferretdb on success)."
    echo "========================================================================"
    export DATABASE="mongodb"
    snapctl set database=mongodb 2>/dev/null || true
fi

# Bring up the chosen database service and stop the other, so exactly one runs on the
# shared port and WeKan does not wait forever for a stopped service. snapctl start --enable
# = snap enable + snap start; targets the snap INSTANCE name so parallel snaps hit their own.
if [ "ferretdb" = "$DATABASE" ]; then
    snapctl start --enable "${WEKAN_SNAP_SVC}.ferretdb" 2>/dev/null || true
    snapctl stop --disable "${WEKAN_SNAP_SVC}.mongodb" 2>/dev/null || true
elif [ "true" != "${DISABLE_MONGODB}" ]; then
    snapctl start --enable "${WEKAN_SNAP_SVC}.mongodb" 2>/dev/null || true
    snapctl stop --disable "${WEKAN_SNAP_SVC}.ferretdb" 2>/dev/null || true
fi

export NODE_PATH=$SNAP/bin
# Use user-provided MONGO_URL if set, otherwise build from components
if [ -n "$MONGO_URL" ]; then
    echo "Using user-provided MONGO_URL"
elif [ "nill" != "$MONGODB_BIND_UNIX_SOCKET" ] && [ "x" != "x$MONGODB_BIND_UNIX_SOCKET" ]; then
    if [ -d $MONGODB_BIND_UNIX_SOCKET ]; then
        export MONGO_URL="mongodb://$MONGODB_BIND_UNIX_SOCKET/mongodb-${MONGODB_PORT}.sock/wekan"
    else
        export MONGO_URL="mongodb://$SNAP_DATA/shared/$MONGODB_BIND_UNIX_SOCKET/wekan"
    fi
else
    [ "x" == "x$MONGODB_BIND_IP" ] && MONGODB_BIND_IP="127.0.0.1"
    export MONGO_URL="mongodb://$MONGODB_BIND_IP:$MONGODB_PORT/wekan"
    # FerretDB v1 has no replica-set oplog, so only advertise MONGO_OPLOG_URL for
    # real MongoDB; with FerretDB, WeKan falls back to polling automatically.
    if [ -z "$MONGO_OPLOG_URL" ] && [ "ferretdb" != "${DATABASE}" ]; then
        export MONGO_OPLOG_URL="mongodb://$MONGODB_BIND_IP:$MONGODB_PORT/local?replicaSet=rs0"
    fi
fi

# If WRITABLE_PATH is not set, use $SNAP_COMMON/files
# Wekan will store attachments there.
if [ -z "$WRITABLE_PATH" ]; then
    export WRITABLE_PATH="$SNAP_COMMON/files"
fi
# Create attachments and avatars directories
mkdir -p "$WRITABLE_PATH/attachments"
mkdir -p "$WRITABLE_PATH/avatars"
echo -e "Using WRITABLE_PATH: $WRITABLE_PATH"

echo -e "MONGO_URL=$MONGO_URL"

# The readiness checks below use db-eval (the bundled Node.js 24 + the `mongodb`
# driver from the WeKan bundle), so there is no mongosh binary — nothing to install
# and nothing phoning home. db-eval speaks the wire protocol to both FerretDB v1
# and MongoDB 6/7.
DB_EVAL="$SNAP/bin/db-eval"
MONGO_PORT="${MONGODB_PORT:-27019}"
MONGO_HOST="${MONGODB_BIND_IP:-127.0.0.1}"
# directConnection so admin commands reach this exact node (also before a replica
# set is initiated).
DB_URL="mongodb://${MONGO_HOST}:${MONGO_PORT}/?directConnection=true"

if [ "ferretdb" = "${DATABASE}" ]; then
    # FerretDB v1 has no replica set / oplog — just wait until it accepts
    # connections, then start WeKan (which uses polling for reactivity).
    # Make sure the FerretDB service is actually enabled and running first; if it was
    # left stopped/disabled (failed migration hand-off, manual stop, crash) enable and
    # start it now (snapctl start --enable = snap enable + snap start) so WeKan does not
    # wait here forever.
    snapctl start --enable "${WEKAN_SNAP_SVC}.ferretdb" 2>/dev/null || true
    echo "Waiting for FerretDB to accept connections on ${MONGO_HOST}:${MONGO_PORT}..."
    until "$DB_EVAL" ping "$DB_URL" >/dev/null 2>&1; do
        echo "FerretDB not ready yet, retrying in 5 seconds..."
        sleep 5
    done
    echo "FerretDB is ready."
elif [ "true" != "${DISABLE_MONGODB}" ]; then
    # Make sure the MongoDB service is enabled and running first; if it was left
    # stopped/disabled, enable and start it now so WeKan does not wait here forever.
    snapctl start --enable "${WEKAN_SNAP_SVC}.mongodb" 2>/dev/null || true
    # Wait for MongoDB replica set primary to be ready before starting WeKan.
    # With changeStreams, Meteor requires the replica set primary to be elected.
    # Large databases can take minutes to replay the WiredTiger journal after a snap update.
    echo "Waiting for MongoDB replica set primary..."
    # After WEKAN_DB_WAIT_TIMEOUT seconds (default 120) print the English upgrade
    # guidance once, then keep retrying (large databases can take minutes to
    # replay the WiredTiger journal after a snap update).
    WEKAN_DB_WAIT_TIMEOUT=${WEKAN_DB_WAIT_TIMEOUT:-120}
    db_waited=0
    db_hint_shown=false
    until "$DB_EVAL" primary "$DB_URL" >/dev/null 2>&1; do
        if [ "$db_hint_shown" != "true" ] && [ "$db_waited" -ge "$WEKAN_DB_WAIT_TIMEOUT" ]; then
            echo ""
            echo "========================================================================"
            echo "WeKan: still cannot connect to MongoDB."
            echo ""
            echo "If you just upgraded WeKan or MongoDB, the existing database may have"
            echo "been created by an OLDER MongoDB version that the new MongoDB cannot"
            echo "open, so MongoDB never finishes starting and WeKan keeps waiting here."
            echo ""
            echo "Upgrade the database - dump with the old version, restore with the new:"
            echo "  1. Start the OLD, previously-working MongoDB version."
            echo "  2. Back up:   mongodump --archive=wekan.archive --gzip"
            echo "  3. Stop old MongoDB. Start the NEW MongoDB on an EMPTY data dir."
            echo "  4. Restore:   mongorestore --archive=wekan.archive --gzip --drop"
            echo "  5. Start WeKan again."
            echo ""
            echo "Attachments and avatars are stored ON DISK under WRITABLE_PATH, NOT"
            echo "in MongoDB, so when moving to a new server ALSO copy that whole"
            echo "directory (it contains 'files', 'attachments' and 'avatars'):"
            echo "  - Snap:   $SNAP_COMMON/files"
            echo "  - Docker: the 'wekan-files' volume mounted at /data"
            echo "  - Source: the WRITABLE_PATH you configured"
            echo ""
            echo "Also check the MongoDB log (snap logs ${SNAP_NAME:-wekan}.mongodb) for"
            echo "the real reason: incompatible featureCompatibilityVersion, wrong mongod"
            echo "version, or an unclean shutdown needing 'mongod --repair'."
            echo "========================================================================"
            echo ""
            db_hint_shown=true
        fi
        echo "MongoDB not ready yet, retrying in 5 seconds..."
        sleep 5
        db_waited=$((db_waited + 5))
    done
    echo "MongoDB replica set primary is ready."
fi

APPLICATION_DIRECTORY=$SNAP
APPLICATION_START=main.js
cd $APPLICATION_DIRECTORY
#$NODE_PATH/node $APPLICATION_START
#---------------------------------------------------------------------
# https://github.com/wekan/wekan/issues/3585#issuecomment-1021522132
# Add more Node heap:
#   export NODE_OPTIONS="--max_old_space_size=4096"
# Add more stack:
#   bash -c "ulimit -s 65500; exec node --stack-size=65500 main.js"
#---------------------------------------------------------------------
#bash -c "ulimit -s 65500; exec $NODE_PATH/node --stack-size=65500 $APPLICATION_START"
#bash -c "ulimit -s 65500; exec $NODE_PATH/node --stack-size=65500 --max-old-space-size=8192 $APPLICATION_START"
bash -c "ulimit -s 65500; exec $NODE_PATH/node $APPLICATION_START"
