#!/usr/bin/env bash
#
# STRYKE WP — Build distributable .zip
# Usage: cd stryke-wp && bash build.sh
# Works on Windows (Git Bash / PowerShell) and Linux/macOS
#
set -euo pipefail

PLUGIN_SLUG="stryke-wp"
VERSION=$(grep -oP "Version:\s*\K[0-9.]+" "${PLUGIN_SLUG}.php" 2>/dev/null || echo "1.0.0")
BUILD_DIR="../build"
ZIP_NAME="${PLUGIN_SLUG}-${VERSION}.zip"

echo "=== Building ${PLUGIN_SLUG} v${VERSION} ==="

# Clean previous build
rm -rf "${BUILD_DIR}"
mkdir -p "${BUILD_DIR}/${PLUGIN_SLUG}"

# Directories to include
for dir in assets languages src; do
  [ -d "$dir" ] && cp -r "$dir" "${BUILD_DIR}/${PLUGIN_SLUG}/"
done

# Root files to include
for file in stryke-wp.php uninstall.php readme.txt CHANGELOG.md; do
  [ -f "$file" ] && cp "$file" "${BUILD_DIR}/${PLUGIN_SLUG}/"
done

# Build zip using PowerShell (Windows) or zip (Linux/macOS)
cd "${BUILD_DIR}"
if command -v zip &>/dev/null; then
  zip -r "../${ZIP_NAME}" "${PLUGIN_SLUG}/" -q
else
  # Windows: use PowerShell Compress-Archive
  ABSPATH=$(cd "${PLUGIN_SLUG}" && pwd -W 2>/dev/null || pwd)
  ZIPPATH=$(cd .. && pwd -W 2>/dev/null || pwd)/"${ZIP_NAME}"
  powershell -NoProfile -Command "Compress-Archive -Path '${ABSPATH}/*' -DestinationPath '${ZIPPATH}' -Force"
  # Wrap in folder: PowerShell archives flat, so we re-package
  # Actually Compress-Archive preserves folder structure when using -Path on a dir
  rm -f "../${ZIP_NAME}"
  PARENT=$(pwd -W 2>/dev/null || pwd)
  powershell -NoProfile -Command "Compress-Archive -Path '${PARENT}/${PLUGIN_SLUG}' -DestinationPath '${ZIPPATH}' -Force"
fi

cd ..

# Report
ZIP_SIZE=$(du -h "${ZIP_NAME}" | cut -f1)
FILE_COUNT=$(zipinfo -1 "${ZIP_NAME}" 2>/dev/null | wc -l || echo "?")

echo "=== Done ==="
echo "  File:  ${ZIP_NAME}"
echo "  Size:  ${ZIP_SIZE}"
echo "  Files: ${FILE_COUNT}"

# Cleanup build dir
rm -rf "${BUILD_DIR}"
