#!/bin/sh
#
# Repack zotero-note-editor_<version>.orig.tar.xz.  Called by
# `debian/rules get-orig-source`; VERSION= overrides the version, which
# otherwise comes from the top entry of debian/changelog.
#
# zotero/note-editor has never been tagged, so the tree is the commit Zotero
# pins, whole: nothing is removed from it.  This is a maintainer tool: it needs
# network access and is never run by a build.

set -eu

PKG=zotero-note-editor
ROOT=$(cd "$(dirname "$0")/.." && pwd)

# The note-editor commit zotero/zotero
# 433c109b7128aa80c01840310386bb90908ea8a7 (11.0-beta.2) pins.
COMMIT=7439a18414ffa6e90918283da9e4dbd35fce1a97
UPVERSION=0.0~git20261006

VERSION=${1:-${VERSION:-}}
if [ -z "$VERSION" ]; then
	VERSION=$(dpkg-parsechangelog -l"$ROOT/debian/changelog" -SVersion |
		sed -e 's/^[0-9]*://' -e 's/-[^-]*$//')
fi
if [ "$VERSION" != "$UPVERSION" ]; then
	printf 'get-orig-source: debian/changelog is %s, this script knows %s\n' \
		"$VERSION" "$UPVERSION" >&2
	exit 1
fi

TARBALL=$ROOT/../${PKG}_${VERSION}.orig.tar.xz

log() { printf 'get-orig-source: %s\n' "$*" >&2; }

WORK=$(mktemp -d)
trap 'rm -rf "$WORK"' EXIT
STAGE=$WORK/$PKG-$VERSION
mkdir -p "$STAGE"

log "fetching zotero/note-editor @ $COMMIT"
curl -4 -fsSL --retry 3 --retry-all-errors --retry-delay 5 --max-time 3600 \
	-o "$WORK/upstream.tar.gz" "https://codeload.github.com/zotero/note-editor/tar.gz/$COMMIT"
tar xzf "$WORK/upstream.tar.gz" -C "$STAGE" --strip-components=1

log "packing $TARBALL"
rm -f "$TARBALL"
tar --sort=name --owner=0 --group=0 --numeric-owner \
	-cJf "$TARBALL" -C "$WORK" "$PKG-$VERSION"
log "$(stat -c '%s bytes' "$TARBALL")"
