#!/bin/sh
set -e

mkdir -p /app/data /app/public/roms /app/public/covers /app/public/bios

# Seed catalog JSON when the data volume is empty
if [ ! -f /app/data/games.json ] && [ -f /app/data-seed/games.json ]; then
  cp /app/data-seed/games.json /app/data/games.json
fi

if [ ! -f /app/data/user-games.json ]; then
  echo '[]' > /app/data/user-games.json
fi

# Seed ROM files when the roms volume is empty (do not overwrite uploads)
if [ -d /app/roms-seed ]; then
  cp -rn /app/roms-seed/. /app/public/roms/ 2>/dev/null || true
fi

# Bind mounts from the host are often owned by root/UID 1000 — nextjs can't write.
# Fix ownership at boot (entrypoint starts as root, then drops privileges).
chown -R nextjs:nodejs /app/data /app/public/roms /app/public/covers /app/public/bios 2>/dev/null || true
chmod -R u+rwX,a+rX /app/data /app/public/roms /app/public/covers /app/public/bios 2>/dev/null || true

exec su-exec nextjs "$@"
