#!/bin/sh
set -e

cd /app/apps/api

if [ "${RUN_MIGRATIONS_ON_START:-false}" = "true" ]; then
  echo "[api] running migrations..."
  until npx prisma migrate deploy; do
    echo "[api] waiting for database..."
    sleep 2
  done
  npx prisma generate
else
  echo "[api] skipping startup migrations (RUN_MIGRATIONS_ON_START=false)"
fi

if [ "$SEED_DATABASE" = "true" ]; then
  echo "[api] seeding database..."
  node dist/infrastructure/database/seed-cli.js
fi

if [ -d /app/uploads-default/banners ] && [ ! -f /app/uploads/banners/welcome.svg ]; then
  echo "[api] copying default banner uploads..."
  mkdir -p /app/uploads/banners
  cp -r /app/uploads-default/banners/. /app/uploads/banners/
fi

echo "[api] starting server..."
exec node dist/main.js
