#!/usr/bin/env bash
#
# Fix 404 for /_next/static/* by copying .next/static into standalone.
# Run on the server when the app loads but CSS/JS chunks return 404.
#
# Use when:
# - You built on the server (npm run build) and never copied static into standalone, or
# - The tarball was created without the build_nextjs_artifact.sh copy step.
#
# From project root on server:
#   sudo bash scripts/fix_nextjs_static.sh
#
set -e

APP_ROOT="${APP_ROOT:-/var/www/boundary-fastapiandnextjs}"
NEXT_DIR="$APP_ROOT/plagis-nextjs"
STANDALONE_STATIC="$NEXT_DIR/.next/standalone/.next/static"
SOURCE_STATIC="$NEXT_DIR/.next/static"

echo "Fix _next/static 404: copy .next/static into standalone"
echo ""

if [ ! -d "$SOURCE_STATIC" ]; then
  echo "Error: $SOURCE_STATIC not found."
  echo "You need a full Next.js build (npm run build) in plagis-nextjs first."
  echo "Or re-deploy using a tarball from: bash scripts/build_nextjs_artifact.sh"
  exit 1
fi

echo "Copying $SOURCE_STATIC -> $STANDALONE_STATIC"
mkdir -p "$NEXT_DIR/.next/standalone/.next"
rm -rf "$STANDALONE_STATIC"
cp -r "$SOURCE_STATIC" "$STANDALONE_STATIC"
echo "Done. Restarting nextjs..."
systemctl restart nextjs
sleep 2
if systemctl is-active --quiet nextjs; then
  echo "nextjs is running. Test: curl -sI http://127.0.0.1:3000/_next/static/chunks/"
else
  echo "nextjs failed to start. Run: journalctl -u nextjs -n 30 --no-pager"
  exit 1
fi
