#!/usr/bin/env bash
set -e

# Ensure permissions on volume and logs directory
mkdir -p /data/db /var/log/mongodb /var/run/mongodb
chown -R mongodb:mongodb /data/db /var/log/mongodb /var/run/mongodb

echo "Starting local MongoDB server (only accessible from inside container)..."
# Start mongod as default mongodb user, bound to localhost (127.0.0.1)
if ! su -s /bin/bash -c "mongod --dbpath /data/db --bind_ip 127.0.0.1 --fork --logpath /var/log/mongodb/mongod.log" mongodb; then
    echo "ERROR: Failed to fork mongod process."
    if [ -f /var/log/mongodb/mongod.log ]; then
        echo "=== MongoDB Log (/var/log/mongodb/mongod.log) ==="
        cat /var/log/mongodb/mongod.log
    fi
    exit 1
fi

echo "Waiting for MongoDB to be ready..."
READY=0
for i in $(seq 1 30); do
    if mongosh --eval "db.adminCommand('ping')" --quiet &>/dev/null; then
        READY=1
        echo "MongoDB is ready."
        break
    fi
    sleep 1
done

if [ "$READY" -ne 1 ]; then
    echo "ERROR: MongoDB did not become ready within 30 seconds!"
    if [ -f /var/log/mongodb/mongod.log ]; then
        echo "=== MongoDB Log (/var/log/mongodb/mongod.log) ==="
        tail -n 100 /var/log/mongodb/mongod.log
    fi
    exit 1
fi

echo "Starting Nginx reverse proxy..."
if ! nginx; then
    echo "ERROR: Failed to start Nginx."
    exit 1
fi

echo "Starting Node.js backend connected to local MongoDB..."
# Start the Node.js API server using MongoDB
exec node server/api-mongodb.js

