#!/usr/bin/env bash
#
# Deploy helper for the API server (fast path).
#
# Pulls the latest code, clears caches AS THE WEB USER (so log/cache files stay
# web-owned and you don't hit "could not be opened in append mode"), and reloads
# PHP so OPcache picks up changed classes.
#
# Run ./fix-permissions.sh ONCE first (after the first deploy) to set up
# ownership + group-writable perms. After that, this script alone is enough.
#
# Usage:
#   ./deploy.sh
#   WEB_USER=nginx APP_DIR=/var/www/html/api.v4 ./deploy.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"

echo "==> git pull"
sudo git pull

echo "==> clearing caches as $WEB_USER"
sudo -u "$WEB_USER" php artisan config:clear
sudo -u "$WEB_USER" php artisan cache:clear
sudo -u "$WEB_USER" php artisan route:clear

# A plain `git pull` does NOT clear PHP's OPcache: if OPcache runs with
# validate_timestamps=0, the web SAPI keeps serving the old compiled bytecode,
# so a changed class (e.g. a fixed `use` import) never takes effect until PHP is
# reloaded. `php -r 'opcache_reset()'` on the CLI won't help — that's a separate
# OPcache from the web SAPI. So gracefully reload the running PHP here.
# Best-effort: never fail the deploy if no service matches.
echo "==> reloading PHP so OPcache picks up changed classes"
reload_php() {
    # Prefer php-fpm (resets its OPcache); fall back to the web server for
    # mod_php setups. Reload (not restart) so in-flight requests aren't dropped.
    for svc in \
        php-fpm php8.4-fpm php8.3-fpm php8.2-fpm php8.1-fpm php8.0-fpm \
        php7.4-fpm php7.3-fpm php7.2-fpm \
        httpd apache2 nginx; do
        if systemctl status "$svc" >/dev/null 2>&1; then
            if sudo systemctl reload "$svc" >/dev/null 2>&1; then
                echo "    reloaded $svc"
                return 0
            fi
        fi
    done
    return 1
}
if ! reload_php; then
    echo "    WARNING: no php-fpm/web service reloaded. If a class change does not"
    echo "    take effect, OPcache may be stale — restart PHP-FPM/Apache manually."
fi

echo "==> done"
