#!/bin/bash

set -e

# Config — adjust as needed
EXCLUDE_FILES=(".wordpress-org" ".github/" "phpcs.xml" "docs/" "*.sh" "make-public.sh" "build-plugin.sh" "includes/classes/admin/assets-dev.php" "README.md")
REMOTE_NAME="public"
REMOTE_BRANCH="main"

read -rp "Enter commit message for public branch update: " COMMIT_MSG
read -rp "Dry run mode? [y/N]: " DRY_RUN_CONFIRM
DRY_RUN=false
if [[ "$DRY_RUN_CONFIRM" =~ ^[Yy]$ ]]; then
  DRY_RUN=true
fi

# Ensure we're on master and up to date
git checkout master
git pull origin master

# Get the current commit hash from master for reference
MASTER_COMMIT=$(git rev-parse HEAD)

# Switch/create public branch
if git show-ref --quiet refs/heads/public; then
    git checkout public
else
    git checkout -b public
fi

# Remove all files in current branch (except .git and .gitignore)
find . -mindepth 1 -maxdepth 1 ! -name '.git' ! -name '.gitignore' -exec rm -rf {} +

# Copy files from master to a temporary directory, then rsync with exclusions
TEMP_DIR=$(mktemp -d)
trap 'rm -rf "$TEMP_DIR"' EXIT

# Extract master branch to temp directory
git archive "$MASTER_COMMIT" | tar -x -C "$TEMP_DIR"

# Build rsync exclusion arguments
RSYNC_EXCLUDES=()
for pattern in "${EXCLUDE_FILES[@]}"; do
  RSYNC_EXCLUDES+=(--exclude="$pattern")
done

# Copy filtered files from temp directory to current directory
rsync -a "${RSYNC_EXCLUDES[@]}" "$TEMP_DIR"/ ./

# Remove any excluded files that might have been copied due to glob patterns
for pattern in "${EXCLUDE_FILES[@]}"; do
  # Handle both files and directories, use find to handle glob patterns safely
  if [[ "$pattern" == *"*"* ]]; then
    # For glob patterns, use find
    find . -name "$pattern" -type f -delete 2>/dev/null || true
  else
    # For specific files/directories
    if [[ "$pattern" == */ ]]; then
      # Directory pattern
      rm -rf "./${pattern%/}" 2>/dev/null || true
    else
      # File pattern
      rm -f "./$pattern" 2>/dev/null || true
    fi
  fi
done

# Stage and commit changes
git add -A

# Check if there are any changes to commit
if git diff --cached --quiet; then
  echo -e "\n⚠️  No changes to commit - public branch is already up to date"
  exit 0
fi

git commit -m "$COMMIT_MSG"

echo -e "\n🧾 Commit that would be pushed:"
git --no-pager log -1 --stat

echo -e "\n📂 Files in this commit:"
git --no-pager diff --name-only HEAD~1 HEAD

if [ "$DRY_RUN" = false ]; then
  read -rp $'\nPush to remote? [y/N]: ' PUSH_CONFIRM
  if [[ "$PUSH_CONFIRM" =~ ^[Yy]$ ]]; then
    git push -f "$REMOTE_NAME" public:"$REMOTE_BRANCH"
    echo -e "\n✅ Public branch pushed to $REMOTE_NAME/$REMOTE_BRANCH"
  else
    echo -e "\n🛑 Push canceled."
  fi
else
  echo -e "\n🛑 Dry run only. No changes were pushed."
fi

echo -e "\n🔒 Excluded patterns:"
printf ' - %s\n' "${EXCLUDE_FILES[@]}"

echo -e "\n📋 Verification - files that should be excluded:"
for pattern in "${EXCLUDE_FILES[@]}"; do
  if [[ "$pattern" == *"*"* ]]; then
    find . -name "$pattern" -type f 2>/dev/null || true
  else
    if [[ -e "$pattern" ]]; then
      echo "  ⚠️  Found: $pattern"
    fi
  fi
done