#!/bin/bash

# MongoDB Control Script
# IMPORTANT: Migration is only triggered when MIGRATE_MONGODB=true environment variable is set
# IMPORTANT: No snap settings or channel changes are made during migration

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

if [ "true" == "${DISABLE_MONGODB}" ]; then
    echo "mongodb is disabled. Stop service"
    snapctl stop --disable ${SNAP_NAME}.mongodb
    exit 0
fi

# Migration checking and handling - controlled by MIGRATE_MONGODB environment variable
MIGRATION_STATUS="${SNAP_COMMON}/mongodb-migration-status.json"
MIGRATION_LOG="${SNAP_COMMON}/mongodb-migration-log.txt"
REVERT_FILE="${SNAP_COMMON}/revert-mongodb-migration.txt"

# Check if migration is needed
check_migration_needed() {
    if [ -f "$MIGRATION_STATUS" ]; then
        local status=$(jq -r '.status' "$MIGRATION_STATUS" 2>/dev/null || echo "unknown")
        if [ "$status" = "completed" ]; then
            return 1
        elif [ "$status" = "running" ]; then
            return 0
        fi
    fi

    # Check if we have MongoDB 3 data
    if [ -d "${SNAP_COMMON}/wekan" ] && [ ! -f "${SNAP_COMMON}/mongodb-version-7" ]; then
        return 0
    fi

    return 1
}

# Handle migration - only if MIGRATE_MONGODB=true
handle_migration() {
    echo "MongoDB migration needed, starting migration process..."

    # Stop Wekan (meteor) process before migration
    echo "Stopping Wekan (meteor) process for migration..."
    snapctl stop --disable ${SNAP_NAME}.wekan || true
    snapctl stop --disable ${SNAP_NAME} || true
    
    # Wait a moment for processes to stop
    sleep 2
    
    # Kill any remaining meteor/node processes
    pkill -f "node.*main.js" || true
    pkill -f "meteor" || true
    sleep 1

    # Start migration web interface in background
    $SNAP/bin/mongodb-migration-web &
    local web_pid=$!
    echo "$web_pid" > "${SNAP_COMMON}/migration-web.pid"

    # Run migration
    if $SNAP/bin/mongodb-migrate; then
        echo "MongoDB migration completed successfully"
        # Kill migration web interface
        if [ -f "${SNAP_COMMON}/migration-web.pid" ]; then
            local web_pid=$(cat "${SNAP_COMMON}/migration-web.pid")
            kill "$web_pid" 2>/dev/null || true
            rm -f "${SNAP_COMMON}/migration-web.pid"
        fi
        
        # Clean up temporary Node.js server file
        rm -f "${SNAP_COMMON}/migration-web-server.js"
        
        echo "Migration completed. Wekan will be restarted automatically."
    else
        echo "MongoDB migration failed"
        # Kill migration web interface
        if [ -f "${SNAP_COMMON}/migration-web.pid" ]; then
            local web_pid=$(cat "${SNAP_COMMON}/migration-web.pid")
            kill "$web_pid" 2>/dev/null || true
            rm -f "${SNAP_COMMON}/migration-web.pid"
        fi
        
        # Clean up temporary Node.js server file
        rm -f "${SNAP_COMMON}/migration-web-server.js"
        
        exit 1
    fi
}

# Check if revert is requested
if [ -f "$REVERT_FILE" ]; then
    echo "Revert requested, stopping Wekan and MongoDB, then reverting migration..."
    
    # Stop Wekan (meteor) process before revert
    echo "Stopping Wekan (meteor) process for revert..."
    snapctl stop --disable ${SNAP_NAME}.wekan || true
    snapctl stop --disable ${SNAP_NAME} || true
    
    # Wait a moment for processes to stop
    sleep 2
    
    # Kill any remaining meteor/node processes
    pkill -f "node.*main.js" || true
    pkill -f "meteor" || true
    sleep 1
    
    # Stop MongoDB
    snapctl stop --disable ${SNAP_NAME}.mongodb
    
    # Run migration (which will handle revert)
    $SNAP/bin/mongodb-migrate
    exit $?
fi

# Check if migration is needed - only if MIGRATE_MONGODB=true
if [ "$MIGRATE_MONGODB" = "true" ]; then
    if check_migration_needed; then
        handle_migration
    else
        echo "MIGRATE_MONGODB=true but no migration needed"
    fi
else
    echo "MIGRATE_MONGODB not set to 'true' - skipping migration check"
fi

# make sure we have set minimum env variables for locale
if [ -z "${LANG}" ]; then
    export LANG=en_US.UTF-8
fi

export LC_ALL=C
# If CPU does not support AVX, use Qemu that supports AVX.
# Migratemongo is at https://github.com/wekan/migratemongo
# and at directory /snap/${SNAP_NAME}/current/migratemongo/avx
# is bash scripts like mongod, mongosh check avx support and use Qemu if needed.
export PATH=/snap/${SNAP_NAME}/current/migratemongo/avx:/snap/${SNAP_NAME}/current/usr/bin:/snap/${SNAP_NAME}/current/bin:${PATH}
export LD_LIBRARY_PATH=/snap/${SNAP_NAME}/current/lib:/snap/${SNAP_NAME}/current/lib/x86_64-linux-gnu:${LD_LIBRARY_PATH}

# If temporary settings log exists, delete it
if [ -f ${SNAP_COMMON}/settings.log ]; then
    rm ${SNAP_COMMON}/settings.log
fi

#if test -f "$SNAP_COMMON/01-migrate-mongo3-to-mongo5.txt"; then
#   touch "$SNAP_COMMON/01-migrate-mongo3-to-mongo5.txt"
#   # Stop MongoDB
#   touch "$SNAP_COMMON/02-disable-mongo.txt"
#   snapctl stop --disable ${SNAP_NAME}.mongodb
#   touch "$SNAP_COMMON/03-eval-stop-mongo.txt"
#   mongo wekan --eval "db.getSiblingDB('admin').shutdownServer()" $BIND_OPTIONS
#   # Start MongoDB 4.4
#   touch "$SNAP_COMMON/04-start-mongo44.txt"
#   $SNAP/mongo44bin/mongod --dbpath $SNAP_COMMON --logpath $SNAP_COMMON/02_mongodb_log_while_migrate.txt --logappend --journal $MONGO_URL --quiet
#   # Wait MongoDB 4.4 to start
#   touch "$SNAP_COMMON/05-wait-2s-mongo44-start.txt"
#   sleep 2s
#   # Dump Old MongoDB 3.x database
#   touch "$SNAP_COMMON/06-dump-database.txt"
#   (cd $SNAP_COMMON && mongodump --port ${MONGODB_PORT})
#   # Stop MongoDB 4.4
#   touch "$SNAP_COMMON/07-stop-mongo44.txt"
#   $SNAP/mongo44bin/mongo wekan --eval "db.getSiblingDB('admin').shutdownServer()" $BIND_OPTIONS
#   # Wait MongoDB 4.4 to stop
#   touch "$SNAP_COMMON/08-wait-2s-mongo44-stop.txt"
#   sleep 2s
#   # Start MongoDB 5
#   touch "$SNAP_COMMON/09-start-mongo5.txt"
#   mongod --dbpath $SNAP_COMMON --logpath $SNAP_COMMON/10_mongodb_log_while_migrate.txt --logappend --journal $MONGO_URL --quiet
#   # Restore database
#   touch "$SNAP_COMMON/11-mongorestore-to-mongo5.txt"
#   (cd $SNAP_COMMON && mongorestore --port ${MONGODB_PORT})
#   # Wait 5s
#   touch "$SNAP_COMMON/12-wait-5s-after-restore.txt"
#   sleep 5s
#   # Shutdown mongodb
#   touch "$SNAP_COMMON/13-shutdown-mongodb.txt"
#   mongo wekan --eval "db.getSiblingDB('admin').shutdownServer()" $BIND_OPTIONS
#   touch "$SNAP_COMMON/14-wait-5s-after-mongo5-shutdown.txt"
#   sleep 5s
#   # Enable MongoDB 5
#   touch "$SNAP_COMMON/15-enable-mongo-5.txt"
#   snapctl start --enable ${SNAP_NAME}.mongodb
#fi
# When starting MongoDB, if logfile exist, delete it, because now uses syslog instead of logfile,
# because syslog usually already has log rotation.
# https://github.com/wekan/wekan-snap/issues/92
#if test -f "$SNAP_COMMON/mongodb.log"; then
#   rm -f "$SNAP_COMMON/mongodb.log"
#fi

# Alternative: When starting MongoDB, and using logfile, truncate log to last 1000 lines of text.
# 1) If file exists:
#if test -f "$SNAP_COMMON/mongodb.log"; then
#    # 2) Copy last 1000 lines to variable loglast1000lines.
#    loglast1000lines=$(tail -1000 "$SNAP_COMMON/mongodb.log")
#    # 3) Copy variable to replace original MongoDB log.
#    echo "$loglast1000lines" > "$SNAP_COMMON/mongodb.log"
#    # 4) Set variable to be empty.
#    loglast1000lines=""
#fi

if [ -z "${MONGO_URL}" ]; then

    # start mongo deamon
    BIND_OPTIONS=""
    if [ "nill" != "${MONGODB_BIND_UNIX_SOCKET}" ] && [ "x" != "x${MONGODB_BIND_UNIX_SOCKET}" ]; then
        BIND_OPTIONS+=" --unixSocketPrefix ${MONGODB_BIND_UNIX_SOCKET}"
    fi
    # Newest MongoDB uses --host or --bind_ip
    if [ "x" != "x${MONGODB_BIND_IP}" ]; then
        BIND_OPTIONS+=" --bind_ip $MONGODB_BIND_IP"
    fi
    if [ "x" != "x${MONGODB_PORT}" ]; then
        BIND_OPTIONS+=" --port ${MONGODB_PORT}"
    fi

    if [ "syslog" == "${MONGO_LOG_DESTINATION}" ]; then
        echo "Sending mongodb logs to syslog"
        mongod --dbpath ${SNAP_COMMON} --syslog ${BIND_OPTIONS} --quiet
        exit 0
    fi

    if [ "snapcommon" == "${MONGO_LOG_DESTINATION}" ]; then
        echo "Sending mongodb logs to $SNAP_COMMON"
        mongod --dbpath ${SNAP_COMMON} --logpath ${SNAP_COMMON}/mongodb.log --logappend ${BIND_OPTIONS} --quiet
    fi

    if [ "devnull" == "${MONGO_LOG_DESTINATION}" ]; then
        echo "Sending mongodb logs to /dev/null"
        mongod --dbpath ${SNAP_COMMON} --logpath /dev/null ${BIND_OPTIONS} --quiet
    fi
    #echo "mongodb log destination: ${MONGO_LOG_DESTINATION}" >> "${SNAP_COMMON}/settings.log"

    # Disable MongoDB telemetry and free monitoring
    /snap/${SNAP_NAME}/current/bin/mongosh wekan --eval 'disableTelemetry();' --port ${MONGODB_PORT}
    /snap/${SNAP_NAME}/current/bin/mongosh wekan --eval 'db.disableFreeMonitoring();' --port ${MONGODB_PORT}

    # Snap: Disable apparmor="DENIED" at syslog
    # https://github.com/wekan/wekan/issues/4855
    /snap/${SNAP_NAME}/current/bin/mongosh wekan --eval 'db.adminCommand({ setParameter: 1, diagnosticDataCollectionEnabled: false});' --port ${MONGODB_PORT}

    # Drop indexes on database upgrade, when starting MongoDB
    #mongosh wekan --eval "db.getCollectionNames().forEach(function(col_name) { var coll = db.getCollection(col_name); coll.dropIndexes(); });" $BIND_OPTIONS

    # Set MongoDB feature compatibility version
    #mongosh wekan --eval 'db.adminCommand({ setFeatureCompatibilityVersion: "4.4" });' ${BIND_OPTIONS}

    # Delete incomplete uploads so that they would not prevent starting WeKan
    /snap/${SNAP_NAME}/current/bin/mongosh wekan --eval 'db.getCollection("cfs.attachments.filerecord").find( { "uploadedAt": { "$exists": true }, "copies.attachments" : null,"failures.copies.attachments.doneTrying" : {"$ne" : true}});' --port ${MONGODB_PORT}

else

    if [ "syslog" == "${MONGO_LOG_DESTINATION}" ]; then
        echo "Sending mongodb logs to syslog"
        mongod --dbpath ${SNAP_COMMON} --syslog ${MONGO_URL} --quiet
    fi

    if [ "snapcommon" == "${MONGO_LOG_DESTINATION}" ]; then
        echo "Sending mongodb logs to ${SNAP_COMMON}"
        mongod --dbpath ${SNAP_COMMON} --logpath ${SNAP_COMMON}/mongodb.log --logappend ${MONGO_URL} --quiet
    fi

    if [ "devnull" == "${MONGO_LOG_DESTINATION}" ]; then
        echo "Sending mongodb logs to /dev/null"
        mongod --dbpath ${SNAP_COMMON} --logpath /dev/null ${MONGO_URL} --quiet
    fi

    # Disable MongoDB telemetry and free monitoring
    /snap/${SNAP_NAME}/current/bin/mongosh ${MONGO_URL} --eval 'disableTelemetry();'
    /snap/${SNAP_NAME}/current/bin/mongosh ${MONGO_URL} --eval 'db.disableFreeMonitoring();'

    # Snap: Disable apparmor="DENIED" at syslog
    # https://github.com/wekan/wekan/issues/4855
    /snap/${SNAP_NAME}/current/bin/mongosh ${MONGO_URL} --eval 'db.adminCommand({ setParameter: 1, diagnosticDataCollectionEnabled: false});'

    # Drop indexes on database upgrade, when starting MongoDB
    #mongosh wekan --eval "db.getCollectionNames().forEach(function(col_name) { var coll = db.getCollection(col_name); coll.dropIndexes(); });" $BIND_OPTIONS

    # Set MongoDB feature compatibility version
    #/snap/${SNAP_NAME}/current/bin/mongosh ${MONGO_URL} --eval 'db.adminCommand({ setFeatureCompatibilityVersion: "4.4" });'

    # Delete incomplete uploads so that they would not prevent starting WeKan
    /snap/${SNAP_NAME}/current/bin/mongosh ${MONGO_URL} --eval 'db.getCollection("cfs.attachments.filerecord").find( { "uploadedAt": { "$exists": true }, "copies.attachments" : null,"failures.copies.attachments.doneTrying" : {"$ne" : true}});'

fi
