#!/usr/bin/env bash
#
# Re-applies world-readable/writable permissions after running artisan/composer/
# phpunit as this user. The web server (nginx) is not in this user's group, and
# this user's shell umask (0007) strips "other" read access from every file it
# creates — so any Blade view/cache Laravel recompiles becomes unreadable to
# nginx the moment it's touched, causing a 500. Run this after any command that
# might have created or rewritten files under the project (artisan, composer,
# phpunit, etc.).
#
# Usage: ./pf.sh

cd "$(dirname "$0")"

# Some compiled views/cache files under storage/ get created by nginx itself
# (owned by the nginx user), so this user's chmod on those specific files will
# fail with "Operation not permitted" — that's expected and harmless (nginx
# already owns them with correct permissions), not a real error to abort on.

echo "==> Making project tree world-readable"
find . -not -path "./.git/*" -type d -exec chmod o+rx {} + 2>/dev/null
find . -not -path "./.git/*" -type f -exec chmod o+r {} + 2>/dev/null

echo "==> Fixing storage & cache write permissions (775)"
chmod -R 775 storage bootstrap/cache 2>/dev/null
find storage bootstrap/cache -type d -exec chmod 775 {} + 2>/dev/null
find storage bootstrap/cache -type f -exec chmod 664 {} + 2>/dev/null

# Compiled Blade views get cached under a hash filename shared by whichever
# process (this user's CLI or nginx/php-fpm's own user) compiles them first.
# When ownership crosses between the two, the other side's later recompile
# attempt fails with "touch(): Utime failed: Operation not permitted" and the
# request 500s. These are pure caches — safe to wipe and let Laravel rebuild.
echo "==> Clearing stale compiled view cache"
php8.5 artisan view:clear 2>/dev/null || php artisan view:clear 2>/dev/null || find storage/framework/views -type f -name "*.php" -delete 2>/dev/null

echo "==> Done."
