#!/bin/bash

# Repack py-tree-sitter and include extra files in the orig tarball.
#
# This is necessary because upstream doesn't provide all the necessary
# files to build the project from the Github tarball.  Instead, it
# adds these files to the PyPi tarball.  OTOH, it doesn't add
# documentation/examples to the PyPi tarball, only to the Github
# tarball.  So we just mix them together here.
#
# See https://github.com/tree-sitter/py-tree-sitter/issues/409

# This script assumes that it will be called like:
#
#   SCRIPT --upstream-version VERSION
#
# It also assumes that it will be invoked from inside the source tree.
#
# It works with uscan v4.

set -exo pipefail

die()
{
    printf "E: %s\n" "$*"
    exit 1
}

readonly UPSTREAM_VERSION="${2}"
TARBALL=$(realpath -e "../py-tree-sitter_${UPSTREAM_VERSION}.orig.tar.gz")
readonly TARBALL
TARDIR=$(dirname "${TARBALL}")
readonly TARDIR
PYPI_TARBALL="tree-sitter-${UPSTREAM_VERSION}.tar.gz"
readonly PYPI_TARBALL
readonly NEW_ORIG_TARBALL="${TARDIR}/py-tree-sitter_${UPSTREAM_VERSION}+repack.orig.tar.xz"

TMPDIR=$(mktemp -d)
readonly TMPDIR
trap 'rm -rf "${TMPDIR}"' EXIT ERR INT

cd "${TMPDIR}"
wget "https://pypi.debian.net/tree-sitter/${PYPI_TARBALL}" \
    || die "Could not find py-tree-sitter version ${UPSTREAM_VERSION} on pypi.debian.net"

mkdir -p "src/py-tree-sitter-${UPSTREAM_VERSION}/"
tar xf "${TARBALL}" -C "src/py-tree-sitter-${UPSTREAM_VERSION}/" --strip-components=1

mkdir pypi-tarball
tar xf "${PYPI_TARBALL}" -C pypi-tarball/ --strip-components=1

cp -a pypi-tarball/tree_sitter/core/ "src/py-tree-sitter-${UPSTREAM_VERSION}/tree_sitter/"

cd src
tar cJf "${NEW_ORIG_TARBALL}" "py-tree-sitter-${UPSTREAM_VERSION}"
