#!/bin/sh
#
# Repack zotero_<version><+dsN>.orig.tar.gz.  Called by `debian/rules
# get-orig-source`; VERSION= overrides the upstream version taken from
# debian/changelog and DS= the +dsN suffix.
#
# The 11.0 line has no release tag, so the tree is the commit the official
# 11.0-beta.2 build was cut from.  The submodules are pinned by that commit and
# the ones nothing in Debian provides are unpacked here; what is left out is
# whatever debian/copyright's Files-Excluded names -- that file is the only
# place to edit.
#
# Maintainer tool: needs network access and is never run by a build.

set -eu

PKG=zotero
ROOT=$(cd "$(dirname "$0")/.." && pwd)
COMMIT=433c109b7128aa80c01840310386bb90908ea8a7
COMMIT_DATE="2026-10-27 02:28:17 UTC"
UPVERSION=11.0~beta.2

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

CHANGELOG_VERSION=$(dpkg-parsechangelog -l"$ROOT/debian/changelog" -SVersion |
	sed 's/^[0-9]*://')
VERSION=${VERSION:-$(printf '%s\n' "$CHANGELOG_VERSION" |
	sed -e 's/-[^-]*$//' -e 's/+ds[0-9]*$//')}
DS=${DS:-$(printf '%s\n' "$CHANGELOG_VERSION" |
	sed -n 's/^[^-]*\(+ds[0-9]*\)-[^-]*$/\1/p')}
if [ "$VERSION" != "$UPVERSION" ]; then
	log "debian/changelog is $VERSION, this script knows $UPVERSION"
	exit 1
fi
if [ -z "$DS" ]; then
	log "debian/changelog carries no +dsN suffix"
	exit 1
fi
TARBALL=$ROOT/../${PKG}_${VERSION}${DS}.orig.tar.gz

# Submodules the orig carries, as <path>|<GitHub repository>.  Those left out
# are the ones Files-Excluded names.
KEEP="translators|zotero/translators
styles|zotero/bundled-styles
chrome/content/zotero/locale/csl|citation-style-language/locales
chrome/content/zotero/xpcom/translate|zotero/translate
chrome/content/zotero/xpcom/utilities|zotero/utilities
resource/schema/global|zotero/zotero-schema"

EPOCH=$(date -u -d "$COMMIT_DATE" +%s)
WORK=$(mktemp -d)
trap 'rm -rf "$WORK"' EXIT
STAGE=$WORK/$PKG-$VERSION
mkdir -p "$STAGE"

log "fetching zotero/zotero $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/zotero/tar.gz/$COMMIT"
tar xzf "$WORK/upstream.tar.gz" -C "$STAGE" --strip-components=1
if [ "$(cat "$STAGE/version")" != 11.0.SOURCE ]; then
	log "unexpected version file: $(cat "$STAGE/version")"
	exit 1
fi

log "reading the submodule pins"
curl -4 -fsS --retry 3 --max-time 120 -o "$WORK/tree.json" \
	"https://api.github.com/repos/zotero/zotero/git/trees/$COMMIT?recursive=1"
python3 - "$WORK/tree.json" > "$WORK/gitlinks" <<'PY'
import json, sys
for e in json.load(open(sys.argv[1]))["tree"]:
    if e["mode"] == "160000":
        print("%s %s" % (e["path"], e["sha"]))
PY

while IFS='|' read -r path repo; do
	[ -n "${path:-}" ] || continue
	sha=$(awk -v p="$path" '$1 == p {print $2}' "$WORK/gitlinks")
	if [ -z "$sha" ]; then
		log "no pin for $path"
		exit 1
	fi
	log "  $path <- $repo @ $sha"
	rm -rf "${STAGE:?}/$path"
	mkdir -p "$STAGE/$path"
	curl -4 -fsSL --retry 3 --retry-all-errors --retry-delay 5 --max-time 3600 \
		-o "$WORK/sub.tar.gz" "https://codeload.github.com/$repo/tar.gz/$sha"
	tar xzf "$WORK/sub.tar.gz" -C "$STAGE/$path" --strip-components=1
done <<EOF
$KEEP
EOF

# The submodules left out are in the export as empty directories.  Files-Excluded
# names them, but mk-origtargz keeps the directory of one that had files in it,
# so the validation below would still see it: drop them here instead.
printf '%s\n' "$KEEP" | cut -d'|' -f1 > "$WORK/keep"
while read -r path sha; do
	[ -n "${path:-}" ] || continue
	grep -qxF "$path" "$WORK/keep" || rm -rf "${STAGE:?}/$path"
done < "$WORK/gitlinks"

find "$STAGE" -type d -exec chmod 755 {} +
find "$STAGE" -type f -exec chmod 644 {} +

log "packing the upstream tarball"
tar --sort=name --owner=0 --group=0 --numeric-owner --mtime="@$EPOCH" \
	-czf "$WORK/$PKG-$VERSION.tar.gz" -C "$WORK" "$PKG-$VERSION"

# mk-origtargz applies Files-Excluded from debian/copyright and writes
# zotero_<version><+dsN>.orig.tar.gz next to the debian/ directory.
(cd "$ROOT" && mk-origtargz --compression gzip --copy \
	"$WORK/$PKG-$VERSION.tar.gz")
[ -f "$TARBALL" ] || { log "no $TARBALL"; exit 1; }

# The submodules skipped above are in the export as empty directories, so
# Files-Excluded has to name them; this fails if one of them is left in.
tar tzf "$TARBALL" | python3 -c '
import sys
top, pin, keep = sys.argv[1], sys.argv[2], set(sys.argv[3:])
names = {l.strip().rstrip("/") for l in sys.stdin if l.strip()}
left = ["%s/%s" % (top, p.split()[0]) for p in open(pin)
        if p.split() and p.split()[0] not in keep]
present = [p for p in left if p in names]
if present:
    sys.exit("submodule not unpacked and not in Files-Excluded: "
             + ", ".join(present))
' "$PKG-$VERSION" "$WORK/gitlinks" $(printf '%s\n' "$KEEP" | cut -d'|' -f1)

log done
sha256sum "$TARBALL"
