#!/bin/sh
set -e

# Fix permissions for mounted volumes (host dirs may be root-owned on first
# run — Docker auto-creates missing bind-mount sources as root:root).
# /media's :ro parent mount cannot be chowned, but the :rw subdirs that
# media-api writes into can — and that's all the process needs.
# /app/logs is shared with the api container via the ./api:/app dev mount;
# api's entrypoint already chowns it but media-api may start independently.
if [ "$(id -u)" = "0" ]; then
  for d in /media/local/inbox /media/local/thumbnails /media/local/photos \
           /media/local/documents /media/public /app/logs; do
    [ -d "$d" ] && chown -R node:node "$d" 2>/dev/null || true
  done
fi

# Drop to node user if running as root (production image uses su-exec).
if [ "$(id -u)" = "0" ] && command -v su-exec >/dev/null 2>&1; then
  exec su-exec node "$@"
else
  exec "$@"
fi
