#!/usr/bin/env bash
# Fix Laravel storage/bootstrap permissions on cPanel (common cause of 503 via web while CLI works)
set -euo pipefail

APP_DIR="${1:-${PWD}}"
cd "${APP_DIR}"

echo "== Fixing permissions in ${APP_DIR} =="

mkdir -p \
  storage/app/public \
  storage/framework/cache/data \
  storage/framework/sessions \
  storage/framework/views \
  storage/logs \
  bootstrap/cache

chmod -R ug+rwx storage bootstrap/cache 2>/dev/null || true
chmod -R 775 storage bootstrap/cache 2>/dev/null || true

# Shared hosting: web PHP often runs as a different user than SSH; 777 is a last resort.
if [[ "${CPANEL_PERMS_777:-false}" == "true" ]]; then
  chmod -R 777 storage bootstrap/cache
  echo "Applied 777 to storage and bootstrap/cache (CPANEL_PERMS_777=true)."
fi

touch storage/logs/laravel.log 2>/dev/null || true
chmod 664 storage/logs/laravel.log 2>/dev/null || true

echo "bootstrap/cache:"
ls -la bootstrap/cache | head -5
echo ""
echo "Done. Reset OPcache in cPanel, then hard-refresh the browser."
