#!/usr/bin/env bash
# Garante que storage/ e bootstrap/cache sejam graváveis pelo PHP-FPM após deploy/composer.
# Evita: file_put_contents(.../storage/framework/views/...): Permission denied
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT" || exit 0

WRITABLE_DIRS=(
  storage/app
  storage/framework/cache
  storage/framework/sessions
  storage/framework/views
  storage/logs
  bootstrap/cache
)

for dir in "${WRITABLE_DIRS[@]}"; do
  [[ -d "$dir" ]] || mkdir -p "$dir" 2>/dev/null || true
  chmod -R ug+rwx "$dir" 2>/dev/null || chmod -R 775 "$dir" 2>/dev/null || true
done

# VPS/dev: PHP-FPM costuma rodar como www-data
if getent group www-data >/dev/null 2>&1; then
  chgrp -R www-data storage bootstrap/cache 2>/dev/null || true
  find storage/framework/views -maxdepth 1 -name '*.php' -user "$(id -un)" -exec chgrp www-data {} + 2>/dev/null || true
fi

exit 0
