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

ROOT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
ENV_FILE="${ROOT_DIR}/credentials/.env"

if [[ -f "${ENV_FILE}" ]]; then
  # shellcheck disable=SC1090
  source "${ENV_FILE}"
fi

VERSION=""
while [[ $# -gt 0 ]]; do
  case "$1" in
    --version)
      VERSION="${2:-}"
      shift 2
      ;;
    --help|-h)
      cat <<'USAGE'
Create a plugin package artifact from ./code.

Usage:
  scripts/package_plugin.sh [--version X.Y.Z]

Notes:
- If --version is not provided, reads Version from code/calendar-plugin.php.
- Writes zip + manifest to ./package.
USAGE
      exit 0
      ;;
    *)
      echo "[package] unknown argument: $1" >&2
      exit 2
      ;;
  esac
done

CURRENT_VERSION="$(sed -n 's/^ \* Version: \(.*\)$/\1/p' "${ROOT_DIR}/code/calendar-plugin.php" | head -n1 | tr -d '[:space:]')"

if [[ -z "${CURRENT_VERSION}" ]]; then
  echo "[package] unable to detect plugin version from code/calendar-plugin.php" >&2
  exit 1
fi

if [[ -z "${VERSION}" ]]; then
  if [[ "${CURRENT_VERSION}" =~ ^([0-9]+)\.([0-9]+)\.([0-9]+)$ ]]; then
    VERSION="${BASH_REMATCH[1]}.${BASH_REMATCH[2]}.$((BASH_REMATCH[3] + 1))"
  else
    echo "[package] current version is not semantic (X.Y.Z): ${CURRENT_VERSION}" >&2
    exit 1
  fi
fi

sed -Ei "s/^ \* Version: .*/ * Version: ${VERSION}/" "${ROOT_DIR}/code/calendar-plugin.php"
sed -Ei "s/('version' => ')[^']+(',)/\1${VERSION}\2/" "${ROOT_DIR}/code/src/Plugin.php"

SLUG="calendar-plugin"
PACKAGE_DIR="${ROOT_DIR}/package"
STAGING_DIR="${PACKAGE_DIR}/staging/${SLUG}"
ARTIFACT="${PACKAGE_DIR}/${SLUG}-${VERSION}.zip"
MANIFEST="${PACKAGE_DIR}/${SLUG}-${VERSION}.manifest.sha256"

mkdir -p "${PACKAGE_DIR}/staging"
rm -rf "${STAGING_DIR}"
mkdir -p "${STAGING_DIR}"

rsync -a --delete "${ROOT_DIR}/code/" "${STAGING_DIR}/"

(
  cd "${PACKAGE_DIR}/staging"
  zip -qr "${ARTIFACT}" "${SLUG}"
)

(
  cd "${STAGING_DIR}"
  find . -type f -print0 | sort -z | xargs -0 sha256sum
) > "${MANIFEST}"

echo "[package] version: ${CURRENT_VERSION} -> ${VERSION}"
echo "[package] created artifact: ${ARTIFACT}"
echo "[package] created manifest: ${MANIFEST}"
