#!/bin/sh
set -e

# Check if $UID and $GID are set, else fallback to default (1000:1000)
USER_ID=${UID:-1000}
GROUP_ID=${GID:-1000}

# Fix file ownership and permissions using the passed UID and GID
echo "Fixing file permissions with UID=${USER_ID} and GID=${GROUP_ID}..."
chown -R ${USER_ID}:${GROUP_ID} /var/www || echo "Some files could not be changed"

# Ensure storage and bootstrap/cache have proper permissions
echo "Setting storage and cache permissions..."
chmod -R 775 /var/www/html/storage /var/www/html/bootstrap/cache
chown -R www-data:www-data /var/www/html/storage /var/www/html/bootstrap/cache

echo "Running migrations..."
/var/www/html/docker/common/wait-for-it.sh database:5432 -t 30 && php artisan migrate --force

# Clear configurations to avoid caching issues in development
# make wait-for-it.sh executable
# use wait for it to wait for database before running optimize:clear
echo "Clearing Cache..."
php artisan optimize:clear

# Run the default command (e.g., php-fpm or bash)
exec "$@"