#!/usr/bin/env bash
# Build a distributable Inkscape extension zip at dist/boxbot-<version>.zip
#
# Usage:
#   ./package.sh [version] [--sign]
#
#   version   Set the version explicitly (used as-is, no bump). Saved to VERSION.
#             With no version, the patch number in VERSION is incremented (x.y.Z+1).
#   --sign    Also produce a detached GPG signature (dist/boxbot-<version>.zip.sig).
#
# The zip bundles only the extension's own files in a boxbot/ folder. It does
# NOT include deps/ — the extension falls back to the inkex shipped with
# Inkscape (the sys.path shim is a no-op when deps/ is absent).
set -euo pipefail

repo_root="$(cd "$(dirname "$0")" && pwd)"
cd "$repo_root"

# Files that go into the package (allowlist: anything not here is excluded).
files="boxbot.inx boxbot.py offset.py placements.py livinghinge.py LICENSE README.md"
pkg="boxbot"

# Increment the patch component of a MAJOR.MINOR.PATCH version string.
bump_patch() {
  local major minor patch
  IFS='.' read -r major minor patch <<< "$1"
  printf '%s.%s.%s' "${major:-0}" "${minor:-0}" "$(( ${patch:-0} + 1 ))"
}

version=""
sign=0
while [ $# -gt 0 ]; do
  case "$1" in
    --sign) sign=1 ;;
    -*) echo "error: unknown option: $1" >&2; exit 1 ;;
    *) version="$1" ;;
  esac
  shift
done

if [ -z "$version" ]; then
  current="$(cat VERSION 2>/dev/null || true)"
  [ -n "$current" ] || { echo "error: no VERSION file to increment" >&2; exit 1; }
  version="$(bump_patch "$current")"
fi

# Persist so the next run increments from here.
printf '%s\n' "$version" > VERSION

stage="$(mktemp -d)"
trap 'rm -rf "$stage"' EXIT
mkdir -p "$stage/$pkg"
for f in $files; do
  [ -f "$f" ] || { echo "error: missing file: $f" >&2; exit 1; }
  cp "$f" "$stage/$pkg/"
done

mkdir -p dist
out="dist/boxbot-${version}.zip"
rm -f "$out"
( cd "$stage" && zip -rq "$repo_root/$out" "$pkg" )

if [ "$sign" -eq 1 ]; then
  rm -f "$out.sig"
  gpg --output "$out.sig" --detach-sign "$out"
  echo "signed -> $out.sig"
fi

echo "built $out"
unzip -l "$out"
