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

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

PLUGIN_SLUG="${PLUGIN_SLUG:-feca_mailshots_plugin}"
SOURCE_DIR="${SOURCE_DIR:-${REPO_ROOT}/${PLUGIN_SLUG}}"
OUTPUT_DIR="${OUTPUT_DIR:-${REPO_ROOT}/dist}"

usage() {
  cat <<'USAGE'
Usage: scripts/package_plugin.sh [--source /path/to/plugin] [--output /path/to/dist]

Creates a versioned, uploadable WordPress plugin zip from the plugin directory.

Defaults:
  source: ./feca_mailshots_plugin
  output: ./dist
USAGE
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --source)
      SOURCE_DIR="${2:-}"
      shift 2
      ;;
    --output)
      OUTPUT_DIR="${2:-}"
      shift 2
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "Unknown argument: $1" >&2
      usage >&2
      exit 1
      ;;
  esac
done

if [[ ! -d "${SOURCE_DIR}" ]]; then
  echo "Error: source directory not found: ${SOURCE_DIR}" >&2
  exit 1
fi

PLUGIN_BASENAME="$(basename "${SOURCE_DIR}")"
PLUGIN_MAIN_FILE="${SOURCE_DIR}/${PLUGIN_BASENAME}.php"
if [[ ! -f "${PLUGIN_MAIN_FILE}" ]]; then
  echo "Error: plugin main file not found: ${PLUGIN_MAIN_FILE}" >&2
  exit 1
fi

if [[ ! -x "${INSTALL_SCRIPT}" ]]; then
  echo "Error: install script not found or not executable: ${INSTALL_SCRIPT}" >&2
  exit 1
fi

if ! command -v zip >/dev/null 2>&1; then
  echo "Error: 'zip' command is required but not installed." >&2
  exit 1
fi

VERSION="$(awk '
  /Version:/ {
    line = $0
    sub(/^.*Version:[[:space:]]*/, "", line)
    if (match(line, /^[0-9]+\.[0-9]+\.[0-9]+/)) {
      print substr(line, RSTART, RLENGTH)
      exit
    }
  }
' "${PLUGIN_MAIN_FILE}")"

if [[ -z "${VERSION}" ]]; then
  echo "Error: could not parse semantic version from ${PLUGIN_MAIN_FILE}" >&2
  exit 1
fi

mkdir -p "${OUTPUT_DIR}"
TMP_DIR="$(mktemp -d)"
trap 'rm -rf "${TMP_DIR}"' EXIT

STAGE_DIR="${TMP_DIR}/${PLUGIN_BASENAME}"
mkdir -p "${STAGE_DIR}"

"${INSTALL_SCRIPT}" --skip-node

if [[ ! -f "${REPO_ROOT}/vendor/autoload.php" ]]; then
  echo "Error: vendor/autoload.php is missing after dependency install." >&2
  exit 1
fi
php "${REPO_ROOT}/scripts/validate_composer_vendor.php" "${REPO_ROOT}/vendor"

rsync -a \
  --delete \
  --exclude '.git/' \
  --exclude '.DS_Store' \
  --exclude '.codex/' \
  --exclude '.idea/' \
  --exclude '.vscode/' \
  --exclude 'node_modules/' \
  --exclude 'vendor/' \
  "${SOURCE_DIR}/" "${STAGE_DIR}/"

mkdir -p "${STAGE_DIR}/vendor"
rsync -a --delete "${REPO_ROOT}/vendor/" "${STAGE_DIR}/vendor/"
php "${REPO_ROOT}/scripts/validate_composer_vendor.php" "${STAGE_DIR}/vendor"

ARCHIVE_PATH="${OUTPUT_DIR}/${PLUGIN_BASENAME}-${VERSION}.zip"
rm -f "${ARCHIVE_PATH}"

(
  cd "${TMP_DIR}"
  zip -qr "${ARCHIVE_PATH}" "${PLUGIN_BASENAME}"
)

echo "Created package: ${ARCHIVE_PATH}"
