#!/bin/bash -e

# Enable jemalloc for reduced memory usage and latency.
if [ -z "${LD_PRELOAD+x}" ]; then
    LD_PRELOAD=$(find /usr/lib -name libjemalloc.so.2 -print -quit)
    export LD_PRELOAD
fi

# If starting the Rails server (with or without extra args, or via thrust), prepare the DB once.
run_db_prepare=false
prev=
for arg in "$@"; do
  if [[ "$prev" == "./bin/rails" || "$prev" == "bin/rails" || "$prev" == "/api/bin/rails" ]]; then
    if [[ "$arg" == "server" ]]; then
      run_db_prepare=true
      break
    fi
  fi
  prev=$arg
done
if [[ "$run_db_prepare" == true ]]; then
  ./bin/rails db:prepare
fi

exec "${@}"
