#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
VERSION="$(grep -m1 '^Version:' "$ROOT_DIR/Ai-Auto-Tool.php" | awk '{print $2}')"
BUILD_DIR="${BUILD_DIR:-/tmp/ai-auto-tool-release}"
ZIP_FILE="${ZIP_FILE:-/tmp/ai-auto-tool-${VERSION}.zip}"

"$ROOT_DIR/tools/check-release.sh"

blocked_files="$(find "$ROOT_DIR" \
  -path "$ROOT_DIR/.svn" -prune -o \
  -path "$ROOT_DIR/vendor/freemius" -prune -o \
  -type f \( \
    -name '*.backup' -o \
    -name '*.bak' -o \
    -name '*.old' -o \
    -name '*.tmp' -o \
    -name 'verify-*.php' -o \
    -name 'test-*.php' -o \
    -name 'LOAD_ME_FIRST.txt' \
  \) -print)"

if [ -n "$blocked_files" ]; then
  echo "Blocked release files found:"
  echo "$blocked_files"
  exit 1
fi

rm -rf "$BUILD_DIR" "$ZIP_FILE"
mkdir -p "$BUILD_DIR/ai-auto-tool"
rsync -a --exclude='.svn' "$ROOT_DIR/" "$BUILD_DIR/ai-auto-tool/"

(cd "$BUILD_DIR" && zip -qr "$ZIP_FILE" ai-auto-tool)

du -sh "$BUILD_DIR/ai-auto-tool" "$ZIP_FILE"
echo "Release package: $ZIP_FILE"
