#!/bin/bash
# Salin build Vite (frontend/dist) ke api/public agar satu domain → api/public.
# Mempertahankan index.php dan .htaccess Laravel.
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
DIST="$ROOT/frontend/dist"
PUBLIC="$ROOT/api/public"

if [ ! -f "$DIST/index.html" ]; then
  echo "ERROR: $DIST/index.html tidak ada. Jalankan: cd frontend && npm run build"
  exit 1
fi

echo "==> Sync SPA → api/public (tanpa menimpa index.php / .htaccess)"
mkdir -p "$PUBLIC/assets"

# Hapus asset SPA lama
rm -rf "$PUBLIC/assets"
# Salin index.html + assets + file statis lain (.htaccess dist jika ada, dll.)
# Jangan timpa index.php / .htaccess Laravel
rsync -a --delete \
  --exclude index.php \
  --exclude .htaccess \
  --exclude '.htaccess' \
  "$DIST/" "$PUBLIC/"

if [ -f "$DIST/.htaccess" ]; then
  echo "(abaikan $DIST/.htaccess — pakai $PUBLIC/.htaccess Laravel+SPA)"
fi

echo "Selesai. Document Root: $PUBLIC"
echo "Tes: curl -sS \"\${APP_URL:-https://padeberkinem.ramaboedi.com}/api/health\""
