#!/bin/bash -e

./bin/prepare-aiven-ssl

rails_server_start=false
if [ "${1}" = "./bin/rails" ] && [ "${2}" = "server" ]; then
  rails_server_start=true
fi
if [ "${1}" = "bundle" ] && [ "${2}" = "exec" ] && [ "${3}" = "rails" ] && [ "${4}" = "server" ]; then
  rails_server_start=true
fi
if [ "${1}" = "bundle" ] && [ "${2}" = "exec" ] && [ "${3}" = "puma" ]; then
  rails_server_start=true
fi

if [ "${rails_server_start}" = true ]; then
  if [ "${RAILS_ENV}" = "production" ]; then
    if [ -z "${DB_HOST:-}" ] || [ "${DB_HOST}" = "127.0.0.1" ]; then
      echo "ERROR: Production requires Aiven DB_HOST (Render → Environment). See docs/environment-variables.md"
      exit 1
    fi
    if [ -z "${DB_PASSWORD:-}${FARM_BACKEND_DATABASE_PASSWORD:-}" ]; then
      echo "ERROR: Set DB_PASSWORD in Render Environment."
      exit 1
    fi
  fi
  ./bin/rails db:prepare
fi

exec "${@}"
