#!/bin/bash
set -euo pipefail

echo "🚀 Starting WP dist build..."

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
cd "$REPO_ROOT"

# Safety check
if [ ! -f ".distignore" ]; then
  echo "❌ .distignore not found in repo root"
  exit 1
fi

# update this array based on your movable folders
HEAVY_DIRS=(
  "node_modules"
  "dev_quizpress"
)

BACKUP_DIR="$(mktemp -d /tmp/wp-dist-backup-XXXXXX)"

# Restore function (always runs)
restore() {
  echo "♻️ Restoring heavy folders..."

  for dir in "${HEAVY_DIRS[@]}"; do
    if [ -d "$BACKUP_DIR/$dir" ]; then
      echo "Restoring $dir"
      if ! mv "$BACKUP_DIR/$dir" "$REPO_ROOT/"; then
        echo "Failed to restore $dir"
        exit 1
      fi
    else
      echo "Not found: $BACKUP_DIR/$dir"
    fi
  done

  rm -rf "$BACKUP_DIR"
  echo "✅ Restore complete"
}

# Ensure restore ALWAYS runs (success, failure, crash, Ctrl+C)
trap 'restore' EXIT INT TERM

# Move heavy folders away
echo "📦 Moving heavy folders to temp location..."

for dir in "${HEAVY_DIRS[@]}"; do
  if [ -d "$dir" ]; then
    echo "➡️ Moving $dir"

    if [ -z "$dir" ] || [ "${dir#/}" != "$dir" ] || [[ "$dir" == *".."* ]]; then
      echo "Refusing to move unexpected path: $dir"
      exit 1
    fi

    # try fast move first
    if ! mv "$dir" "$BACKUP_DIR/"; then
      echo "⚠️ mv failed for $dir, using copy+remove fallback"

      if ! cp -a "$dir" "$BACKUP_DIR/"; then
        echo "Failed to copy $dir to backup"
        exit 1
      fi

      if ! rm -rf "$dir"; then
        echo "Failed to remove original $dir after backup copy"
        exit 1
      fi
    fi
  fi
done

# Run WP packaging
echo "📦 Running WP dist-archive..."

wp dist-archive . --force

echo "🎉 Build completed successfully"