#!/bin/bash
set -e

# Wait for the database to accept connections.
echo "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."

# storage/app and public/storage are Docker volumes (survive rebuilds/redeploys), so a
# fresh volume always mounts root-owned regardless of the image's build-time chown —
# reassert ownership on every boot, before anything (including migrate) writes there.
# Only touch paths that actually need it: `chown -R` unconditionally bumps every file's
# ctime, which the file explorer's "created" column relies on as a fallback.
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

# App key (only if not already provided via env).
if [ -z "${APP_KEY}" ] && ! grep -q "APP_KEY=base64" .env 2>/dev/null; then
    php artisan key:generate --force || true
fi

# Schema is owned by Laravel migrations.
php artisan migrate --force

# Optional data load for production (idempotent INSERTs).
if [ "${SEED_ON_DEPLOY}" = "true" ]; then
    echo "Importing initial employee data..."
    php artisan db:seed --force || true
fi

# Cache config/routes/views for performance.
php artisan config:cache
php artisan route:cache
php artisan view:cache

exec "$@"
