#!/usr/bin/env bash
#
# Makes project files readable and grants nginx and devgroup write access to
# Laravel runtime directories. Run after CLI commands that create cache files.
#
# Usage: ./pf.sh (run as the project owner, devgroup)

cd "$(dirname "$0")"

if [[ "$(id -un)" != "$(stat -c %U storage/framework/views)" ]]; then
    echo "Run this script as the owner of storage/framework/views (devgroup)." >&2
    exit 1
fi

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 "==> Granting nginx access to Laravel runtime paths"
# Only the owner can change an ACL. nginx-owned files already allow nginx access.
current_user="$(id -un)"
find storage bootstrap/cache -type d -user "$current_user" \
    -exec setfacl -m u:nginx:rwx,g:devgroup:rwx,d:u:nginx:rwx,d:g:devgroup:rwx {} + 2>/dev/null || true
find storage bootstrap/cache -type f -user "$current_user" \
    -exec setfacl -m u:nginx:rw,g:devgroup:rw {} + 2>/dev/null || true

if ! getfacl -cp storage/framework/views | grep -qx 'user:nginx:rwx'; then
    echo "nginx does not have write access to compiled views." >&2
    exit 1
fi
if ! getfacl -cp storage/framework/views | grep -qx 'default:user:nginx:rwx'; then
    echo "New compiled views will not inherit nginx access." >&2
    exit 1
fi

echo "==> Fixing storage & cache write permissions"
chmod -R 777 storage bootstrap/cache 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

echo "==> Done."
