#!/bin/sh
set -e

# public/uploads (a host bind mount) and storage (a named volume) are both
# mounted over the image after it was built, so the Dockerfile's build-time
# chown never reaches them. A freshly created mount comes up root-owned, which
# leaves php-fpm (www-data) unable to write and makes uploads fail with a
# permission error. Fix ownership on every start; cheap and idempotent.
mkdir -p /var/www/html/public/uploads

# Seed the mount from the copy baked into the image, without ever overwriting.
# `-n` skips any file that already exists, so the repo's photos show up on a
# fresh host while every client-uploaded file is left exactly as it is. If cp
# does not support -n it errors and we skip seeding -- the safe direction to
# fail, since the alternative would be clobbering the client's photos.
if [ -d /opt/seed-uploads ]; then
    cp -rn /opt/seed-uploads/. /var/www/html/public/uploads/ 2>/dev/null || true
fi
chown -R www-data:www-data /var/www/html/public/uploads /var/www/html/storage

php artisan config:clear
php artisan cache:clear
php artisan view:clear

php artisan package:discover --ansi
php artisan config:cache

if [ "$RUN_MIGRATIONS" = "true" ]; then
    php artisan migrate --force
fi

exec supervisord -c /etc/supervisor/conf.d/supervisord.conf
