#!/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

# 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/migratemongo/avx:$SNAP/usr/bin:$SNAP/bin:$PATH
export LD_LIBRARY_PATH=$SNAP/lib:$SNAP/lib/x86_64-linux-gnu:$SNAP/lib/aarch64-linux-gnu:$LD_LIBRARY_PATH

# start mongodb restore
[ "x" == "x${MONGODB_BIND_IP}" ] && MONGODB_BIND_IP="127.0.0.1"
echo "using bind ip: $MONGODB_BIND_IP port: $MONGODB_PORT"
# --drop: drop each collection before restoring to avoid IndexKeySpecsConflict
# when the dump's index specs differ from the existing index definitions
# (e.g. unique flag mismatch after a schema migration).
# Add --noIndexRestore instead of --drop if you need to preserve existing data
# and are happy to let WeKan rebuild indexes on next startup.
mongorestore --host $MONGODB_BIND_IP --port $MONGODB_PORT -d wekan --drop --gzip --archive=$1
