#!/bin/bash
set -e
echo "Worker waiting for MySQL at ${DB_HOST}:${DB_PORT}..."
until php -r "exit(@fsockopen(getenv('DB_HOST'), (int)getenv('DB_PORT')) ? 0 : 1);"; do
    sleep 2
done
echo "MySQL is up. Starting: $*"

# storage/app and public/storage are Docker volumes shared with the app container; a
# fresh mount is root-owned regardless of the image, so reassert ownership on every boot.
# Only touch paths that actually need it (see entrypoint.sh for why).
mkdir -p storage/app public/storage
find storage bootstrap/cache public/storage -not -user www-data -exec chown www-data:www-data {} + 2>/dev/null || true

# Run as www-data (not root): the app container's Apache writes storage/ as www-data,
# and any file this worker creates there (logs, cache, backups/...) must keep that
# ownership or later www-data writes start failing silently.
exec runuser -u www-data -- "$@"
