#!/usr/bin/env bash
# Run on Alpine BE (artc0) as root — installs builder nginx + verifies.
set -euo pipefail

WEB="/var/www/localhost/htdocs/apps/app/androidcast_project"
BUILD_PUBLIC="$WEB/android_cast/examples/build_console/backend/public"
APPS_CONF="/etc/nginx/conf.d/apps.conf"
BUILDER_FRAG="/etc/nginx/conf.d/apps_builder.frag"

if [[ ! -f "$BUILD_PUBLIC/index.php" ]]; then
  echo "Missing $BUILD_PUBLIC/index.php" >&2
  exit 1
fi

cat > "$BUILDER_FRAG" << EOF
location = /app/androidcast_project/build {
	return 301 /app/androidcast_project/build/;
}

location ^~ /app/androidcast_project/build/assets/ {
	alias $BUILD_PUBLIC/assets/;
}

location ^~ /app/androidcast_project/build/ {
	include fastcgi_params;
	fastcgi_pass unix:/run/php-fpm.socket;
	fastcgi_param SCRIPT_FILENAME $BUILD_PUBLIC/index.php;
	fastcgi_param SCRIPT_NAME /app/androidcast_project/build/index.php;
	fastcgi_param REQUEST_URI \$request_uri;
	client_max_body_size 512m;
	fastcgi_read_timeout 1800s;
}
EOF

echo "Wrote $BUILDER_FRAG"
grep SCRIPT_FILENAME "$BUILDER_FRAG"

if ! grep -q 'include /etc/nginx/conf.d/apps_builder.frag' "$APPS_CONF"; then
  echo "WARN: $APPS_CONF does not include apps_builder.frag inside listen 443 server block." >&2
  echo "Add: include /etc/nginx/conf.d/apps_builder.frag;  before the closing } of the 443 server." >&2
fi

nginx -t
rc-service nginx reload

echo
echo "=== effective build locations ==="
nginx -T 2>/dev/null | grep -A6 'androidcast_project/build/' | head -40

echo
echo "=== curl BE :443 ==="
curl -sSI -H 'Host: apps.f0xx.org' 'https://127.0.0.1/app/androidcast_project/build/' -k \
  | grep -E 'HTTP|location|x-powered-by' || true

echo
echo "If still 404, check error log:"
echo "  tail -20 /var/log/nginx/apps.intra.raptor.org.error_log"
