#!/usr/bin/env bash
#
# ONE-TIME permission setup for the API server.
#
# Makes the writable Laravel paths owned by the web user and group-writable,
# with setgid so new files inherit the group. Run this ONCE; after that,
# ./deploy.sh (which clears caches as the web user) is all you need.
#
# It only touches the paths Laravel actually writes to (logs, framework cache,
# bootstrap/cache) — NOT storage/app, which can hold large uploads and would
# make this slow. chmod is batched (-exec ... +) so it's fast even with many
# files.
#
# This can take a little while the first time. To survive an SSH timeout, run
# it detached and watch the log:
#   nohup ./fix-permissions.sh > /tmp/fixperms.log 2>&1 &
#   tail -f /tmp/fixperms.log
#
# Usage:
#   ./fix-permissions.sh
#   WEB_USER=nginx APP_DIR=/var/www/html/api.v4 ./fix-permissions.sh
#
set -euo pipefail

WEB_USER="${WEB_USER:-apache}"          # verify: ps aux | grep -E 'php-fpm|httpd|nginx'
APP_DIR="${APP_DIR:-/var/www/html/api.v4}"

cd "$APP_DIR"

# Only the paths the framework writes to. Add 'storage/app' here yourself if you
# also need uploads reset — but that dir can be large, so it's excluded by default.
PATHS=(storage/logs storage/framework bootstrap/cache)

echo "==> chown -R $WEB_USER:$WEB_USER  (${PATHS[*]})"
sudo chown -R "$WEB_USER:$WEB_USER" "${PATHS[@]}"

echo "==> setgid + group-writable on directories"
sudo find "${PATHS[@]}" -type d -exec chmod 2775 {} +

echo "==> group-writable on files"
sudo find "${PATHS[@]}" -type f -exec chmod 0664 {} +

echo "==> done"
