#!/usr/bin/env bash
set -euo pipefail

APP_ROOT="${APP_ROOT:-/var/www/html/allstocktrading-app}"
RUNTIME_USER="${RUNTIME_USER:-www-data}"
RUNTIME_GROUP="${RUNTIME_GROUP:-www-data}"
HISTORY_SMOKE_CLIENT_ID="${HISTORY_SMOKE_CLIENT_ID:-}"

if [[ "$(id -u)" -ne 0 ]]; then
    echo "This deployment finalizer must run as root so it can normalize runtime ownership." >&2
    exit 1
fi

cd "$APP_ROOT"

chown -R "$RUNTIME_USER:$RUNTIME_GROUP" storage bootstrap/cache
find storage bootstrap/cache -type d -exec chmod 2775 {} +
find storage bootstrap/cache -type f -exec chmod 0664 {} +

run_as_runtime=(runuser -u "$RUNTIME_USER" -- env XDG_CONFIG_HOME=/tmp/ast-deploy-config php artisan)
"${run_as_runtime[@]}" optimize:clear
"${run_as_runtime[@]}" app:check-runtime-permissions --owner="$RUNTIME_USER" --group="$RUNTIME_GROUP"

smoke_args=(app:smoke-portal-history)
if [[ -n "$HISTORY_SMOKE_CLIENT_ID" ]]; then
    smoke_args+=("--client=$HISTORY_SMOKE_CLIENT_ID")
fi
"${run_as_runtime[@]}" "${smoke_args[@]}"

"${run_as_runtime[@]}" app:check-runtime-permissions --owner="$RUNTIME_USER" --group="$RUNTIME_GROUP"
echo "Laravel runtime permissions and Portal history smoke check passed."
